gpt4 book ai didi

python - 元素树搜索帮助(python, xml)

转载 作者:行者123 更新时间:2023-12-01 06:11:56 24 4
gpt4 key购买 nike

我正在尝试查找属性 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*']")

我使用 cElementTree 而不是 lxml,因为它在我的计算机上要快得多。

最佳答案

ElementTree 实际上可以做到这一点。

您可能需要使用 .//* 而不是 *

Python docs ElementTree Python 2.7 附带的 1.3.0 版本具有您所寻求的 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>]

关于python - 元素树搜索帮助(python, xml),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com