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

j5shi picture j5shi · May 2, 2012 · Viewed 78.6k times · Source

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.

Thanks.

Answer

Eli Bendersky picture Eli Bendersky · May 2, 2012

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']