If you want children who are nlevels deep in the tree and then iterate over them, you can do:
def childrenAtLevel(tree, n):
if n == 1:
for child in tree.getchildren():
yield child
else:
for child in tree.getchildren():
for e in childrenAtLevel(child, n-1):
yield e
Then, to get the elements at four levels in depth, you simply say:
for e in childrenAtLevel(root, 4):
Or, if you want to get all leaf nodes (i.e. nodes that themselves do not have any children), you can do:
def getLeafNodes(tree):
if len(tree) == 0:
yield tree
else:
for child in tree.getchildren():
for leaf in getLeafNodes(child):
yield leaf
source
share