how to iterate through every element of a complicated XML tree

自闭症网瘾萝莉.ら 提交于 2019-12-12 05:18:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!