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

2024-04-27 22:43:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这种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 in根.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的所有元素?


Tags: nameidnodeinitvaluetypebodyxml
3条回答

对于2.6+相当于kalgasnik的Elementree代码,只需将iter()替换为getiterator():

import xml.etree.ElementTree as ET
tree = ET.fromstring("""...""")
for  elt in tree.getiterator():
    print "%s: '%s'" % (elt.tag, elt.text.strip())

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

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.dom.minidom并不重要:

import xml.etree.ElementTree as ET
tree = ET.fromstring("""...""")
for  elt in tree.iter():
    print "%s: '%s'" % (elt.tag, elt.text.strip())

输出:

program: ''
type: 'Program'
body: ''
type: 'VariableDeclaration'
declarations: ''
type: 'VariableDeclarator'
id: ''
type: 'Identifier'
name: 'answer'
init: ''
type: 'BinaryExpression'
operator: '*'
left: ''
type: 'Literal'
value: '6'
right: ''
type: 'Literal'
value: '7'
kind: 'var'

相关问题 更多 >