You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

包含®实体的XML数据无法读取解析、无法转JSON如何处理?

XML 包含 ® 无法正常读取的解决方案

问题原因

XML 规范默认仅支持 5 种预定义实体:<、>、&、"、',®属于HTML扩展实体,未在XML中声明时解析器会报实体未定义错误,导致XML无法正常加载。

可落地解决方法

  • 方案一:给XML解析器补充实体声明
    无需修改原始XML内容,在初始化解析器时添加缺失的实体映射即可,以下为Python lxml库的示例代码:
from lxml import etree

# 初始化XML解析器,补充reg实体的映射规则
parser = etree.XMLParser()
parser.entitydefs['reg'] = '®'

# 加载XML内容
raw_xml = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns3:Envelope xmlns="http://www.testesb.com/schemas/esb/common/Envelope" xmlns:ns2="http://www.test.com" xmlns:ns3="com.bbby.schemas.esb.common.envelope">
                        <ns2:MasterShortDescription>The Air Fryer lets you to enjoy your favorite fried snacks and food without the added calories. Cooks food by circulating hot air in all directions and includes 8 presets pre-heat, fries, pork, shrimp, cake chicken, steak and fish</ns2:MasterShortDescription>
                        <ns2:MasterProductDescription>3.7 qt. &reg; Digital Air Fryer with 8 Presets in Plum</ns2:MasterProductDescription>
                        <ns2:WebProductDescription>3.7 qt. Digital Air Fryer with 8 Presets in Plum</ns2:WebProductDescription>
</ns3:Envelope>"""
root = etree.fromstring(raw_xml.encode('utf-8'), parser=parser)

# 后续可正常读取节点内容,再按规则转换为JSON即可
  • 方案二:预处理XML内容转义特殊实体
    如果无法修改解析器配置,可对原始XML做定向替换:
    • 若要保留&reg;的原始文本格式,将&reg;替换为&amp;reg;
    • 若要展示实际的注册商标符号,将&reg;替换为Unicode字符®
  • 方案三:使用兼容HTML实体的解析工具
    部分XML/HTML通用解析库默认支持常用HTML实体,可直接调用这类工具解析XML,无需额外配置。

注意事项

不要全局替换所有&字符,否则会破坏XML本身的预定义实体,导致标签、属性的转义逻辑失效。如果后续要转换为JSON,建议直接将&reg;转换为对应Unicode字符,JSON对原生Unicode支持友好,不会出现二次转义问题。

内容的提问来源于stack exchange,提问作者naresh chinna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:06:02