开发者

Possible to search for XML elements by a sub-element's text value in lxml?

开发者 https://www.devze.com 2023-04-12 22:05 出处:网络
I have an XML file with a structure like this: <index> <compound kind=\"file\"> <name>file.c<开发者_如何学运维/name>

I have an XML file with a structure like this:

<index>
    <compound kind="file">
        <name>file.c<开发者_如何学运维/name>
        <member kind="variable"><name>foo</name></member>
        <member kind="variable"><name>bar</name></member>
        ...
    </compound>
    <compound kind="file">
        <name>file.h></name>
        <member>...
    </compound>
</index>

I need to search by file member name but I can't figure out if there is a way that avoids iterating the entire tree. My solution currently looks like:

for f in xmlroot.iter("compound"):
    for m in f.iter("member"):
        if m.find("name").text == my_var_name:
            print "Found"

Is there a way to use a dict() search to improve efficiency because I actually have another for loop above that that goes through the list of variables to search for so performance-wise this is really poor.

Would changing those two for loops to a single XPath search improve performance?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号