191

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

George
  • 15,241
  • 22
  • 66
  • 83

4 Answers4

331

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.

Stevoisiak
  • 23,794
  • 27
  • 122
  • 225
dgassaway
  • 3,513
  • 2
  • 13
  • 8
  • 11
    The second line can be simply `root = ET.fromstring(xmlstring)`. Equals `ET.parse('file.xml').getroot()`: https://docs.python.org/3.6/library/xml.etree.elementtree.html#parsing-xml – Anton Tarasenko Aug 11 '17 at 17:43
  • 8
    @Anton, as the OP states, the idea is to generate an ElementTree, and not an Element. This is useful, for instance, when you want to use ElementTree.write(). – batbrat May 29 '18 at 12:35
  • If anyone is curious this also works for `lxml` – Louie Bafford Jan 28 '22 at 17:36
115

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

rjurney
  • 4,824
  • 5
  • 41
  • 62
Jim H.
  • 5,539
  • 1
  • 24
  • 23
20

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

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
karlcow
  • 6,977
  • 4
  • 38
  • 72
  • 1
    Yes, but this is not an `ElementTree` it is the root `Element`. This API is different and can't do all the same things. – rjurney Sep 20 '21 at 15:34
11

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.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
handle
  • 5,859
  • 3
  • 54
  • 82