Ryan
Ryan

Reputation: 354

Iterate through XML child of a child tags in Python

Currently, I have an XML file. I want to say, if string is this print all the child element associated with this. I've documented some of the code that I've tried. I'm using the element tree built in.

XML

<commands>
    <command name="this" type="out" major="0x1" minor="0x0">
        <data bytes="1-0" descrip=" ID"></data>
        <data bytes="3-2" descrip=" ID"></data>
        <data bytes="5-4" descrip=" ID"></data>
        <data bytes="7-6" descrip="  Code"></data>
        <data bytes="12-8" descrip=" Revision"></data>
        <data bytes="13" descrip=" Version"></data>
        <data bytes="14" descrip="   Mask"></data>
        <data bytes="15" descrip="Reserved"></data>
        <data bytes="17-16" descrip="   Windows"></data>
        <data bytes="19-18" descrip=" of Write Flush Addresses"></data>
    </command>
</commands>

Sample Code to Parse Out Names

tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])

I basically want to dive deeper and print the sub tags of the command name.

Upvotes: 0

Views: 1776

Answers (1)

heinst
heinst

Reputation: 8786

You have to get the children of the child and iterate through all of the grandchildren

tree = ET.parse('command_details.xml')
root = tree.getroot()

for child in root:

    if child.attrib['major'] == str(hex(int(major_bits[::-1], 2))) and child.attrib['minor'] == str(hex(int(minor_bits[::-1], 2))):
        command_name = str(child.attrib['name'])    
        for grandchild in child.getchildren():
            print str(grandchild.attrib['bytes'])
            print str(grandchild.attrib['descrip'])

Or if you want to print the full XML line, you can do:

print ET.tostring(grandchild).strip()

Upvotes: 1

Related Questions