我有这种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的所有元素?
对于2.6+相当于kalgasnik的Elementree代码,只需将iter()替换为getiterator():
这可能最好用递归函数来实现。像这样的东西应该可以做到,但我还没有测试过,所以考虑它的伪代码。
如果使用xml.dom.minidom并不重要:
输出:
相关问题 更多 >
编程相关推荐