Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all sub-elements of an element tree with Python ElementTree?

I want to find a way to get all the sub-elements of an element tree like the way ElementTree.getchildren() does, since getchildren() is deprecated since Python version 2.7.
I don't want to use it anymore, though I can still use it currently.

like image 997
j5shi Avatar asked May 02 '12 06:05

j5shi


People also ask

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

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.


3 Answers

All sub-elements (descendants) of elem:

all_descendants = list(elem.iter()) 

A more complete example:

>>> import xml.etree.ElementTree as ET >>> a = ET.Element('a') >>> b = ET.SubElement(a, 'b') >>> c = ET.SubElement(a, 'c') >>> d = ET.SubElement(a, 'd') >>> e = ET.SubElement(b, 'e') >>> f = ET.SubElement(d, 'f') >>> g = ET.SubElement(d, 'g') >>> [elem.tag for elem in a.iter()] ['a', 'b', 'e', 'c', 'd', 'f', 'g'] 

To exclude the root itself:

>>> [elem.tag for elem in a.iter() if elem is not a] ['b', 'e', 'c', 'd', 'f', 'g'] 
like image 160
Eli Bendersky Avatar answered Sep 19 '22 19:09

Eli Bendersky


in the pydoc it is mentioned to use list() method over the node to get child elements.
list(elem)

like image 45
Harshal Zope Avatar answered Sep 22 '22 19:09

Harshal Zope


If you want to get all elements 'a', you can use:

a_lst = list(elem.iter('a'))

If the elem is also 'a', it will be included.

like image 39
pepr Avatar answered Sep 22 '22 19:09

pepr