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.
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
You need the
from xml.etree.ElementTree import XML, fromstring myxml = fromstring(text)
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))
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.