Python xml ElementTree from a string source?

PythonXml

Python Problem Overview


The ElementTree.parse reads from a file, how can I use this if I already have the XML data in a string?

Maybe I am missing something here, but there must be a way to use the ElementTree without writing out the string to a file and reading it again.

xml.etree.elementtree

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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

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

Solution 4 - Python

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 https://stackoverflow.com/questions/15356641/how-to-write-xml-declaration-using-xml-etree-elementtree.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorgeView Question on Stackoverflow
Solution 1 - PythondgassawayView Answer on Stackoverflow
Solution 2 - PythonJim H.View Answer on Stackoverflow
Solution 3 - PythonkarlcowView Answer on Stackoverflow
Solution 4 - PythonhandleView Answer on Stackoverflow