frankr6591
frankr6591

Reputation: 1247

"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)

Upvotes: 19

Views: 18806

Answers (3)

Pramath Bhat
Pramath Bhat

Reputation: 1

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.

Upvotes: 0

frankr6591
frankr6591

Reputation: 1247

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

Upvotes: 9

alecxe
alecxe

Reputation: 473863

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)

Upvotes: 44

Related Questions