簡體   English   中英

在Python中遍歷子標記的XML子標記

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

目前,我有一個XML文件。 我想說的是,如果string是this ,則打印與this相關的所有子元素。 我已經記錄了一些我嘗試過的代碼。 我正在使用內置的元素樹。

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>

解析名稱的示例代碼

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'])

我基本上想更深入地研究並打印命令名稱的子標簽。

您必須得到孩子的孩子並遍歷所有孫子孫

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'])

或者,如果您要打印完整的XML行,則可以執行以下操作:

print ET.tostring(grandchild).strip()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM