简体   繁体   English

在Python中遍历子标记的XML子标记

[英]Iterate through XML child of a child tags in Python

Currently, I have an XML file. 目前,我有一个XML文件。 I want to say, if string is this print all the child element associated with this . 我想说的是,如果string是this ,则打印与this相关的所有子元素。 I've documented some of the code that I've tried. 我已经记录了一些我尝试过的代码。 I'm using the element tree built in. 我正在使用内置的元素树。

XML 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. 我基本上想更深入地研究并打印命令名称的子标签。

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: 或者,如果您要打印完整的XML行,则可以执行以下操作:

print ET.tostring(grandchild).strip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM