0

I can open and read an XML file.

What I'd like to do is a recursion to print out all child elements of the current node.

The (awful) iterative approach has nested for loops:

root = tree.getroot()
for child in root:
    print (child.tag, child.text)
    for gen1 in child:
        print(child.tag, "\t" , gen1.tag, "\t\t", gen1.text)
        for gen2 in gen1:
            print(child.tag, "\t" , gen1.tag, "\t" ,gen2.tag, "\t\t", gen2.text)
            for gen3 in gen2:
                print(child.tag, "\t" , gen1.tag, "\t" , gen2.tag, "\t", gen3.tag, "\t\t", gen3.text)
                for gen4 in gen3:
                    print(child.tag, "\t" , gen1.tag, "\t" , gen2.tag, "\t", gen3.tag, "\t", gen4.tag, "\t\t", gen4.text)
                    for gen5 in gen4:
                        print(child.tag, "\t" , gen1.tag, "\t" , gen2.tag, "\t", gen3.tag, "\t", gen4.tag, "\t", gen5.tag, "\t\t", gen5.text)
                        for gen6 in gen5:
                            print(child.tag, "\t" , gen1.tag, "\t" , gen2.tag, "\t", gen3.tag, "\t", gen4.tag, "\t", gen5.tag, "\t", gen6.tag, "\t\t", gen6.text)
                            for gen7 in gen6:
                                print(child.tag, "\t" , gen1.tag, "\t" , gen2.tag, "\t", gen3.tag, "\t", gen4.tag, "\t", gen5.tag, "\t", gen6.tag, "\t", gen7.tag, "\t\t", gen7.text)

I can't wrap my head around "this node has no children" for the stop of recursion. Any suggestions?

1 Answer 1

1

Here is a solution, I might get the formatting wrong:

def traverse(node,ances):
    to_print = f"{ances}{node.tag}\t{node.text}"
    print(to_print)
    for child in node:
        traverse(child,to_print+"\t")

traverse(root,"")

You don't need to set explicit stop condition when there isn't any child. Here, there won't be any traverse call inside for loop in that case, and recursion will automatically stop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.