"XML or text declaration not at start of entity: line 2, column 0" when calling ElementTree.parse
Asked Answered
L

3

19

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)
Linctus answered 15/3, 2016 at 19:44 Comment(2)
I also tried saving the xml into a file and open the file.xml... still failed.Linctus
This can happen also when you receive a file or stream that starts with blank spaces.Protasis
I
44

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)
Inbound answered 15/3, 2016 at 19:45 Comment(1)
How do you remove the blank space before the first element?Protasis
L
9

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

Linctus answered 15/3, 2016 at 19:47 Comment(0)
A
0
import xml.etree.ElementTree as ET

xmlExample = 
"""
<?xml version="1.0"?>
<data></data>
"""

tree = ET.fromstring(xmlExample.strip())

You can try this. This worked for me.

Adjunct answered 29/8, 2023 at 6:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.