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

Python读取含未定义实体的大XML文件报错求助

解决XML解析时未定义实体的错误

问题核心是xml.etree.ElementTree仅支持XML标准预定义的5个实体(<、>、&、"、'),像©、–这类HTML扩展实体不在支持范围内,导致解析报错。下面是两种实用解决方法:

方法1:手动替换实体

将XML中的扩展实体直接替换为对应的Unicode字符,适合实体类型较少的场景:

import xml.etree.ElementTree as ET

# 读取XML文件内容
with open('data.xml', 'r', encoding='utf-8') as f:
    xml_content = f.read()

# 定义实体与对应字符的映射
entity_mapping = {
    '©': '©',
    '–': '–',
    '—': '—',
    '®': '®',
    '™': '™'
    # 可根据实际遇到的实体继续添加
}

# 批量替换实体
for entity, char in entity_mapping.items():
    xml_content = xml_content.replace(entity, char)

# 从处理后的字符串解析XML
root = ET.fromstring(xml_content)

方法2:用HTML解码工具自动处理所有实体

Python的html模块可以自动解码所有HTML扩展实体,无需手动维护映射表:

import xml.etree.ElementTree as ET
import html

# 读取XML文件
with open('data.xml', 'r', encoding='utf-8') as f:
    xml_content = f.read()

# 解码所有HTML实体
xml_content = html.unescape(xml_content)

# 解析处理后的XML内容
root = ET.fromstring(xml_content)

注意:如果你的XML文件极大(远超15000行),一次性读取可能占用较多内存,可以改为逐行读取替换后再拼接,不过15000行的规模用上述方法完全没问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:15:32