16

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)
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
frankr6591
  • 1,211
  • 1
  • 8
  • 14

3 Answers3

40

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)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
8

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

frankr6591
  • 1,211
  • 1
  • 8
  • 14
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.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
Pramath Bhat
  • 1
  • 1
  • 1