xml.etree.ElementTree get node depth
import xml.etree.ElementTree as etree
tree = etree.ElementTree(etree.fromstring(rexml))
maxdepth = 0
def depth(elem, level):
"""function to get the maxdepth"""
global maxdepth
if (level == maxdepth):
maxdepth += 1
# recursive call to function to get the depth
for child in elem:
depth(child, level + 1)
depth(tree.getroot(), -1)
print(maxdepth)
The Python ElementTree
API provides iterators for depth-first traversal of a XML tree - unfortunately, those iterators don't provide any depth information to the caller.
But you can write a depth-first iterator that also returns the depth information for each element:
import xml.etree.ElementTree as ET
def depth_iter(element, tag=None):
stack = []
stack.append(iter([element]))
while stack:
e = next(stack[-1], None)
if e == None:
stack.pop()
else:
stack.append(iter(e))
if tag == None or e.tag == tag:
yield (e, len(stack) - 1)
Note that this is more efficient than determining the depth via following the parent links (when using lxml
) - i.e. it is O(n)
vs. O(n log n)
.