I was wondering if python’s own Element Tree API has any native equivalent to lxml’s iterchildren
and iterdescendants
?
From what I can see from the docs the main way to iterate over all the children of an element is to use the iter
function which first yields the element itself before yielding any of the children.
I can always hack them in myself like so:
def iterchildren(root_element:Element) -> Iterator[Element]:
children:list[Element] = root_element.findall("*")
for child in children:
yield child
def iterdescendants(root_element:Element) -> Iterator[Element]:
children:list[Element] = root_element.findall("*")
for child in children:
yield child
if len(child) != 0:
for grandchild in iterdescendants(child):
yield grandchild
which would give:
a = fromstring("""<root><child1><subchild1><subsubchild1></subsubchild1></subchild1></child1><child2></child2></root>""")
for child in iterchildren(a):
print(child.tag)
# child1
# child2
for child in iterdescendants(a):
print(child.tag)
# child1
# subchild1
# subsubchild1
# child2
But I was wondering if there’s a “built-in” way to do this like you can in lxml