[英]Python XML ElementTree not reading node with &
我有一个 XML,其中一个节点在字符串中包含“&”:
<uid>JAMES&001</uid>
现在,当我尝试使用以下代码阅读整个 xml 时:
tree = et.parse(fileName)
root = tree.getroot()
ids = root.findall("uid")
我在上述节点的链接上收到错误:
xml.etree.ElelmentTree.ParseError: not well-formed (invalid token): line17, column 21
该代码在没有“&”的其他情况下工作正常。 估计是断线了
可以用编码修复吗? 如何? 我搜索了其他问题,但找不到答案。
TIA
您需要先对 xml 进行消毒,因为它的形状不正确。
您需要替换有问题的&
- 类似.replace("&", "&")
一种使用方法:
with open(fileName, 'r+') as f:
read_data = f.read()
doc = ET.fromstring(read_data.replace("&", "&"))
print(doc.find('./uid').text)
Output,给定您的样本,应该是
JAMES&001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.