“XML or text declaration not at start of entity: line 2, column 0” when calling ElementTree.parse

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 17:43:38

问题


ElementTree.parse() fails in the simple example below with the error

xml.etree.ElementTree.ParseError: XML or text declaration not at start of entity: line 2, column 0

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)

回答1:


You have a newline at the beginning of the XML string, remove it:

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

Or, you may just strip() the XML string:

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

As a side note, you don't have to create a file-like buffer, and use .fromstring() instead:

root = ET.fromstring(xmlExample)



回答2:


Found it... whitespace in front of 1st element...



来源:https://stackoverflow.com/questions/36020697/xml-or-text-declaration-not-at-start-of-entity-line-2-column-0-when-calling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!