I have a string containing XML data that is returned from an http request.
I am using ElementTree to parse the data, and I want to then search recursively for an element.
According to this question, I can only search recursively with result.findall()
if result
is of type ElementTree
rather than type Element
.
Now xml.etree.ElementTree.fromstring()
, used to parse the string, returns an Element
object, while xml.etree.ElementTree.parse()
, used to parse a file, returns an ElementTree
object.
My question is then: How can I parse the string and get an ElementTree
instance? (without any madness like writing to a temporary file)
There are two ways to parse the file using 'ElementTree' module. The first is by using the parse() function and the second is fromstring() function. The parse () function parses XML document which is supplied as a file whereas, fromstring parses XML when supplied as a string i.e within triple quotes.
The xml.etree.ElementTree module implements a simple and efficient API for parsing and creating XML data. Changed in version 3.3: This module will use a fast implementation whenever available.
To read an XML file using ElementTree, firstly, we import the ElementTree class found inside xml library, under the name ET (common convension). Then passed the filename of the xml file to the ElementTree. parse() method, to enable parsing of our xml file. Then got the root (parent tag) of our xml file using getroot().
When you use ElementTree.fromstring()
what you're getting back is basically the root of the tree, so if you create a new tree like this ElementTree.ElementTree(root)
you'll get you're looking for.
So, to make it clearer:
from xml.etree import ElementTree tree = ElementTree.ElementTree(ElementTree.fromstring(<your_xml_string>))
or:
from xml.etree.ElementTree import fromstring, ElementTree tree = ElementTree(fromstring(<your_xml_string>))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With