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

2024-02-17

我有这种 XML 结构(从 JSON 转换的 Esprima ASL 的输出),它可以比这更加嵌套(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> 

通常对于 XML 我使用for node inroot.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 

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


这可能最好通过递归函数来实现。像这样的东西应该可以做到这一点,但我还没有测试过它,所以考虑它是伪代码。

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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

遍历元素嵌套结构中的所有 XML 节点 的相关文章

随机推荐