元素树搜索帮助(python、xml)

2024-06-16 14:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到属性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上使用celementree,因为它在我的comp上要快得多。在


Tags: 元素属性rootlxmlclassbtscompbcf
1条回答
网友
1楼 · 发布于 2024-06-16 14:19:32

事实上ElementTree可以做到这一点。在

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

python2.7附带的Python docs ElementTree版本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']")

输出

^{pr2}$

相关问题 更多 >