元素树搜索帮助(python,xml)
我想找到所有子元素,这些元素的属性 class
是 'TRX',并且它们的属性 distName
以 'PLMN-PLMN/BSC-208812/BCF-1/BTS-1' 开头。
这样做可以吗?
root[0].findall("*[@class='TRX'][@distName='PLMN-PLMN/BSC-208812/BCF-1/BTS-1*']")
我在用 lxml 的 cElementTree,因为在我的电脑上它快得多。
1 个回答
2
ElementTree 其实可以做到这一点。
你可能需要用 .//*
来代替 *
。
Python 文档中的 ElementTree 版本 1.3.0 是和 Python 2.7 一起发布的,它具备你想要的 XPath 功能。
示例
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']")
输出
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>]