python – “XML或文本声明不在实体的开头:第2行,第0列”,当调用ElementTree.parse时

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)

解决方法:

您在XML字符串的开头有一个换行符,将其删除

xmlExample = """<?xml version="1.0"?>
...

或者,您可以只删除()XML字符串:

source = io.StringIO(xmlExample.strip())

作为旁注,您不必创建类似文件的缓冲区,而是使用.fromstring()

root = ET.fromstring(xmlExample)

相关文章

php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念