如何在 python 中显示 xml 文件中节点的子元素?

How can I display the child element of a node from an xml file, in python?

这是我的 xml 文件

<root>
        <Module name="ac4" offset="32" width="12">
            <register name="xga_control" offset="0x000" width="32" access="R/W">

                <field name="reserved" offset="0" bit_span="5"/>

                <field name="force_all_fault_clear" bit_span="1" default="0">
                    <description>Rising edge forces all fault registers to clear</description>
                </field>

                <field name="force_warning" default="0" bit_span="1">
                    <description>Forces AC2 to report a Master Warning</description>
                </field>

                <field name="force_error" default="0" bit_span="1">
                   <description>Forces AC2 to report a Master Error</description>
                </field>
            </register>
         </Module>

<root>

现在我可以访问我的寄存器的名称并显示它们。但是我还想显示我的字段元素的名称和属性。我怎样才能做到这一点?到目前为止,这是我的代码。

input_file = etree.parse('file1.xml')
output=open("ac4.vhd","w+")

    output.write("Registers \n")
    for node in input_file.iter():
        if node.tag=="register":
            name=node.attrib.get("name")
            print(name)
            output.write(name)
            output.write("\n")
            if node.tag=="field":
                name=node.attrib.get("name")
                output.write(name)

现在输出看起来像

Registers 
xga_control
i_cmd_reg

我希望它看起来像

Registers 
xga_control
    reserved           
    force_all_fault_clear
    force_warning
    force_error
i_cmd_reg
   field name
   field name

关于如何做到这一点有什么想法吗?

您可以 input_file.getroot() 并系统地对其进行迭代,而不是迭代 input_file.iter()

这就是您编写代码的方式:

import xml.etree.ElementTree as ET                                               

tree = ET.parse('file1.xml')                                                     

root = tree.getroot()                                                            

with open('ac4.vhd', 'w+') as fd:                                                
    fd.write('Registers\n')                                                      
    for node in root:                                                            
        if node.tag == 'Module':                                                 
            for sub_node in node:                                                
                fd.write('{0}\n'.format(sub_node.get('name')))                   
                for child in sub_node:                                           
                    fd.write('\t{0}\n'.format(child.get('name')))

您的输出变为:

Registers
xga_control
    reserved
    force_all_fault_clear
    force_warning
    force_error