jck
jck

Reputation: 2058

element tree search help(python, xml)

I'm trying to find all child elements whose attribute class is 'TRX' and whose attribute distName Starts with 'PLMN-PLMN/BSC-208812/BCF-1/BTS-1'

Is something like this possible?

root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']")

I'm using cElementTree over lxml because it is much much faster on my comp.

Upvotes: 1

Views: 931

Answers (1)

kevpie
kevpie

Reputation: 26088

ElementTree can in fact do this.

You may need to use .//* instead of *.

Python docs ElementTree version 1.3.0 which comes with Python 2.7 has the XPath capabilities you seek.

Example

from xml.etree import ElementTree

et = ElementTree.fromstring("""
<r>
    <b>
        <a class='c' foo='e'>this is e</a>
        <a class='c' foo='f'>this is f</a>
        <a class='c' foo='g'>this is g</a>
    </b>
</r>
""")


if __name__ == '__main__':
    print ElementTree.VERSION
    print  "* c and f", et.findall("*[@class='c'][@foo='f']")
    print  ".//* c and f", et.findall(".//*[@class='c'][@foo='f']")
    print  ".//* c", et.findall(".//*[@class='c']")
    print  ".//* f", et.findall(".//*[@foo='f']")

Output

1.3.0
* c and f []
.//* c and f [<Element 'a' at 0x10049be50>]
.//* c [<Element 'a' at 0x10049bdd0>, <Element 'a' at 0x10049be50>, <Element 'a' at 0x10049bf10>]
.//* f [<Element 'a' at 0x10049be50>]

Upvotes: 2

Related Questions