I am trying to iterate over all nodes in a tree using ElementTree.
I do something like:
tree = ET.parse("/tmp/test.xml")
root = tree.getroot()
for child in root:
### do something with child
The problem is that child is an Element object and not ElementTree object, so I can't further look into it and recurse to iterate over its elements. Is there a way to iterate differently over "root" so that it iterates over the top level nodes in the tree (immediate children) and return the same class as root itself?
To iterate over all nodes, use the iter method on the ElementTree, not the root Element.
The root is an Element, just like the other elements in the tree and only really has context of its own attributes and children. The ElementTree has the context for all Elements.
For example, given this xml
You can do the following
you can also access specific elements like this:
then loop over
range(len(country))
and accessAdding to Robert Christie's answer it is possible to iterate over all nodes using
fromstring()
by converting the Element to an ElementTree:In addition to Robert Christie's accepted answer, printing the values and tags separately is very easy: