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.
Advertisement
Answer
All sub-elements (descendants) of elem
:
JavaScript
x
2
1
all_descendants = list(elem.iter())
2
A more complete example:
JavaScript
1
11
11
1
>>> import xml.etree.ElementTree as ET
2
>>> a = ET.Element('a')
3
>>> b = ET.SubElement(a, 'b')
4
>>> c = ET.SubElement(a, 'c')
5
>>> d = ET.SubElement(a, 'd')
6
>>> e = ET.SubElement(b, 'e')
7
>>> f = ET.SubElement(d, 'f')
8
>>> g = ET.SubElement(d, 'g')
9
>>> [elem.tag for elem in a.iter()]
10
['a', 'b', 'e', 'c', 'd', 'f', 'g']
11
To exclude the root itself:
JavaScript
1
3
1
>>> [elem.tag for elem in a.iter() if elem is not a]
2
['b', 'e', 'c', 'd', 'f', 'g']
3