ElementTree.parse()
在下面的简单示例中失败并显示错误
xml.etree.ElementTree.ParseError: XML or text declaration not at start of entity: line 2, column 0
XML看起来有效,代码很简单,所以我做错了什么?
xmlExample = """
<?xml version="1.0"?>
<data>
stuff
</data>
"""
import io
source = io.StringIO(xmlExample)
import xml.etree.ElementTree as ET
tree = ET.parse(source)
解决方法:
xmlExample = """<?xml version="1.0"?>
...
或者,您可以只删除()XML字符串:
source = io.StringIO(xmlExample.strip())
作为旁注,您不必创建类似文件的缓冲区,而是使用.fromstring()
:
root = ET.fromstring(xmlExample)