如何遍历复杂的XML树的每个元素 [英] how to iterate through every element of a complicated XML tree
问题描述
我这样声明了一个根:
root = ET.fromstring(xml_data)
,假设我有一个看起来像这样的XML代码
< a>
< b>
< c>
< d>
< e>
...
< / e>
< / d>
< / c>
< / b>
< / a>
我不太确定如何遍历元素树中的每个元素。 / p>
我已经考虑过要这样做:
while(True)
代表根目录中的孩子
打印child.tag
但这最终以无限输出:
a
a
a
a
a
只是为了让您了解我要执行的操作,我传递了两个XML代码,一个是相当大的,复杂的XML代码,而另一个仅仅是简单的XML代码。
我需要找出大型XML代码中有多少个匹配的XML。
因此,我需要遍历大型XML中的每个元素,并将其与每个小型XML元素进行比较。
任何帮助将不胜感激。谢谢。
任何解决方案都是递归的
process_node(节点n)
对n.text做一些操作(如果存在n.children中的子对象
,则$ n $ child
) code>
在最高级别
process_node(root)
根据需要添加节点名称测试以自定义处理。
I have declared a root this way:
root = ET.fromstring(xml_data)
and let's say I have a XML code that looks like this
<a>
<b>
<c>
<d>
<e>
...
</e>
</d>
</c>
</b>
</a>
I am not too sure how to go about iterating through each of these elements in a element tree.
I've thought about doing :
while (True)
for child in root
print child.tag
but this ended up with this infinite output:
a
a
a
a
a
Just to give you an idea of what I am trying to do, I am passing two XML codes, one is a pretty large and complicated XML code, and the other one is just a simple XML code. I need to find how many matching XML there are in the large XML code.
So, I will need to iterate though each element in the large XML, and compare that with each of the small XML element.
Any help would be appreciated. Thank you.
Any solution is going to be recursive
process_node(node n)
do something with n.text if present
for child in n.children
process_node(child)
And at the top level
process_node(root)
Add tests for node name as needed to customize processing.
这篇关于如何遍历复杂的XML树的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!