[Python] how to recursively iterate over XML tags in Python using ElementTree?

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    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 returns the same class as the root itself?

    Continue reading...

Compartilhe esta Página