Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 442
frankr6591 Avatar asked Mar 15 '16 19:03

frankr6591


2 Answers

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)
like image 130
alecxe Avatar answered Sep 26 '22 05:09

alecxe


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

like image 20
frankr6591 Avatar answered Sep 23 '22 05:09

frankr6591