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)
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)
Found it... whitespace in front of 1st element...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With