“不在实体开始处的XML或文本声明:第2行,第0列,”调用ElementTree.parse时 [英] "XML or text declaration not at start of entity: line 2, column 0" when calling ElementTree.parse
本文介绍了“不在实体开始处的XML或文本声明:第2行,第0列,”调用ElementTree.parse时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的简单示例中,ElementTree.parse()
失败,并显示错误
ElementTree.parse()
fails in the simple example below with the error
xml.etree .ElementTree.ParseError:XML或文本声明不在实体的开头:第2行,第0列
xml.etree.ElementTree.ParseError: XML or text declaration not at start of entity: line 2, column 0
XML看起来有效且代码很简单,那么我在做什么错了?
The XML looks valid and the code is simple, so what am I doing wrong?
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字符串的开头有一个换行符,将其删除:
You have a newline at the beginning of the XML string, remove it:
xmlExample = """<?xml version="1.0"?>
...
或者,您可能只是 strip()
XML字符串:
Or, you may just strip()
the XML string:
source = io.StringIO(xmlExample.strip())
作为旁注,您不必创建类似文件的缓冲区,而使用 .fromstring()
相反:
As a side note, you don't have to create a file-like buffer, and use .fromstring()
instead:
root = ET.fromstring(xmlExample)
这篇关于“不在实体开始处的XML或文本声明:第2行,第0列,”调用ElementTree.parse时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文