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.
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().
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.
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']
in the pydoc it is mentioned to use list() method over the node to get child elements.list(elem)
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.
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