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.
<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>
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.