Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ElementTree: Parsing a string and getting ElementTree instance

Tags:

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)

like image 853
YXD Avatar asked Dec 20 '11 18:12

YXD


People also ask

How do you parse XML from string in Python?

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.

What is Etree in Python?

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.

How do you access XML elements in Python?

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().


1 Answers

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>)) 
like image 111
jcollado Avatar answered Oct 18 '22 23:10

jcollado