The Python Oracle

Python xml ElementTree from a string source?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 Question
00:35 Accepted answer (Score 114)
01:02 Answer 2 (Score 322)
01:28 Answer 3 (Score 20)
01:43 Answer 4 (Score 11)
02:16 Thank you

--

Full question
https://stackoverflow.com/questions/6470...

Question links:
[xml.etree.elementtree]: http://docs.python.org/library/xml.etree...

Accepted answer links:
[xml.etree.ElementTree]: http://docs.python.org/library/xml.etree...

Answer 2 links:
[parse()]: https://docs.python.org/library/xml.etre...
[fromstring()]: https://docs.python.org/library/xml.etre...

Answer 4 links:
[io.StringIO]: https://docs.python.org/library/io.html#...
[xml.etree.ElementTree]: https://docs.python.org/3/library/xml.et...
[ElementTree.write()]: https://docs.python.org/3/library/xml.et...
[How to write XML declaration using xml.etree.ElementTree]: https://stackoverflow.com/questions/1535...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #xml

#avk47



ANSWER 1

Score 343


You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.




ACCEPTED ANSWER

Score 116


If you're using xml.etree.ElementTree.parse to parse from a file, then you can use xml.etree.ElementTree.fromstring to get the root Element of the document. Often you don't actually need an ElementTree.

See xml.etree.ElementTree




ANSWER 3

Score 20


You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)



ANSWER 4

Score 12


io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.