元素树语法错误(格式不正确,标记无效)

Element Tree Syntax Error (not well-formed with invalid token)

我正在尝试使用 Element Tree 模块,但我最终遇到了一些我无法理解的错误。

我这里的代码基于 Python 文档本身,Python Element Tree doc,当我尝试 运行 脚本时,它以某种方式给了我一个错误;

try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET
file_name_xml = "curl-result.xml"
tree = ET.parse(file_name_xml)
tree.getroot()

当我运行这段代码时:

./python2.6 modify_xml_file.py    

然后,它给了我这个错误;

Traceback (most recent call last):
  File "modify_xml_file.py", line 8, in <module>
    tree = ET.parse(file_name_xml)
  File "<string>", line 45, in parse
  File "<string>", line 32, in parse
SyntaxError: not well-formed (invalid token): line 1, column 4

Python 2.6 中包含的 cElementTree 版本抛出 异常 XML:

>>> with open('bad.xml', 'w') as badxml:
...     badxml = '<foobar\n'
...
>>> import xml.etree.cElementTree as ET
>>> tree = ET.parse('bad.xml')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 45, in parse
  File "<string>", line 32, in parse
SyntaxError: no element found: line 1, column 0

这是在 Python 2.7 中修复的 C 加速代码中的错误。 (较慢的)Python 解析器抛出更有用的错误:

>>> import xml.etree.ElementTree as ET
>>> tree = ET.parse('bad.xml')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.6/xml/etree/ElementTree.py", line 862, in parse
    tree.parse(source, parser)
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.6/xml/etree/ElementTree.py", line 587, in parse
    self._root = parser.close()
  File "/Users/mjpieters/Development/Library/buildout.python/parts/opt/lib/python2.6/xml/etree/ElementTree.py", line 1254, in close
    self._parser.Parse("", 1) # end of data
xml.parsers.expat.ExpatError: no element found: line 1, column 0

修复您的 XML 输入文件。

2.7 中的变化是 ElementTree 是 updated to version 1.3, a version that improved the parser,引入了一个新的 ParseError 异常,它是 SyntaxError.

的子类