python中的XML解析:expaterror格式不正确

2024-05-23 16:01:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python的xml.etree.ElementTree对文件进行一些XML解析。但是,我在文档的中间发现了这个错误:

xml.parsers.expat.ExpatError: not well-formed (invalid token): line X, column Y

所以我转到vim中的X行,Y列,我看到了一个带有红色背景突出显示的与号(&;)。这是什么意思?

前面的两个字符也是>>,所以>>&可能有什么特别的地方?

有人知道怎么解决这个问题吗?


Tags: 文件文档token错误notxmletreewell
3条回答

您可以使用xml模块中的escape函数

from xml.sax.saxutils import escape

my_string = "Some string with an &"

# If the string contains &, <, or > they will be converted.
print(escape(my_string))

# Above will return: Some string with an &amp;

引用:Escaping strings for use in XML

&;是XML中的一个特殊字符,用于字符实体。如果XML本身不作为&amp;&#1104;等实体的一部分,则XML无效。

我用yattag代替

from yattag import indent
print indent(xml_string.encode('utf-8'))

相关问题 更多 >