[Python] Recursively search for parent child combinations and build tree in python and XML

Discussão em 'Python' iniciado por Stack, Julho 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to traverse this XML data full of parent->child relationships and need a way to build a tree. Any help will be really appreciated. Also, in this case, is it better to have attributes or nodes for the parent-->child relationship?

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <nodes>
    <node name="Car" child="Engine"/>
    <node name="Car" child="Wheel"/>
    <node name="Engine" child="Piston"/>
    <node name="Engine" child="Carb"/>
    <node name="Carb" child="Bolt"/>
    <node name="Spare Wheel"/>
    <node name="Bolt" child="Thread"/>
    <node name="Carb" child="Foat"/>
    <node name="Truck" child="Engine"/>
    <node name="Engine" child="Bolt"/>
    <node name="Wheel" child="Hubcap"/>
    </nodes>


    On the Python Script, this is what i have. My brain is fried and I cannot get the logic going? please help

    import xml.etree.ElementTree as ET
    tree = ET.parse('rec.xml')
    root = tree.getroot()
    def find_node(data,search):
    #str = root.find('.//node[@child="1.2.1"]')
    for node in data.findall('.//node'):
    if node.attrib['name']==search:
    print('Child-->', node)

    for nodes in root.findall('node'):
    parent = nodes.attrib.get('name')
    child = nodes.attrib.get('child')
    print (parent,'-->', child)
    find_node(root,child)


    A possible output that is expected is something like this (really dont care about the sorting order, As long as all node items are represented somewhere in the tree.

    Car --> Engine --> Piston
    Car --> Engine --> Carb --> Float
    Car --> Engine --> Carb --> Bolt --> Thread
    Car --> Wheel --> Hubcaps
    Truck --> Engine --> Piston
    Truck --> Engine --> Carb --> Bolt --> Thread
    Truck --> Loading Bin
    Spare Wheel -->

    Continue reading...

Compartilhe esta Página