问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/17310681/how-to-iterate-through-every-element-of-a-complicated-xml-tree