遍历元素嵌套结构中的所有 XML 节点 [英] Walk through all XML nodes in an element-nested structure

查看:36
本文介绍了遍历元素嵌套结构中的所有 XML 节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this kind of XML structure (output from the Esprima ASL converted from JSON), it can get even more nested than 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> 

通常对于 XML 我使用 for node inroot.childNodes` 但这仅适用于直接子级:

Usualy for XML I use the for node inroot.childNodes` but this works only for the direct children:

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 的所有元素?

How can I walk all the elements of the XML regardless how many nested elements are?

推荐答案

这可能最好通过递归函数来实现.这样的事情应该可以做到,但我还没有测试过,所以请考虑使用伪代码.

This is probably best achieved with a recursive function. Something like this should do it but I've not tested it so consider it pseudocode.

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)

这篇关于遍历元素嵌套结构中的所有 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆