遍历元素嵌套结构中的所有XML节点

Edu*_*scu 5 python xml minidom python-2.7

我有这种XML结构(从JSON转换而来的Esprima ASL的输出),它可以比this(ASL.xml)更加嵌套:

<?xml version="1.0" encoding="UTF-8" ?>
    <program>
    <type>Program</type>
    <body>
        <type>VariableDeclaration</type>
        <declarations>
            <type>VariableDeclarator</type>
            <id>
                <type>Identifier</type>
                <name>answer</name>
            </id>
            <init>
                <type>BinaryExpression</type>
                <operator>*</operator>
                <left>
                    <type>Literal</type>
                    <value>6</value>
                </left>
                <right>
                    <type>Literal</type>
                    <value>7</value>
                </right>
            </init>
        </declarations>
        <kind>var</kind>
    </body>
    </program> 
Run Code Online (Sandbox Code Playgroud)

for node inUsualy for XML我使用root.childNodes`但这仅适用于直接子节点:

import xml.dom.minidom as  md
dom = md.parse("ASL.xml")
root = dom.documentElement
for node in root.childNodes:
    if node.nodeType == node.ELEMENT_NODE:
        print node.tagName,"has value:",  node.nodeValue:, "and is child of:",node.parentNode.tagName 
Run Code Online (Sandbox Code Playgroud)

无论有多少嵌套元素,我如何遍历XML的所有元素?

red*_*rah 9

这可能是使用递归函数最好的方法.像这样的东西应该这样做,但我没有测试它,所以考虑它伪代码.

import xml.dom.minidom as  md

def print_node(root):
    if root.childNodes:
        for node in root.childNodes:
           if node.nodeType == node.ELEMENT_NODE:
               print node.tagName,"has value:",  node.nodeValue, "and is child of:", node.parentNode.tagName
               print_node(node)

dom = md.parse("ASL.xml")
root = dom.documentElement
print_node(root)
Run Code Online (Sandbox Code Playgroud)