如何在python中搜索具有给定属性值的Xml节点

Abh*_*dra 5 python xml xpath

我有这个 XML 文件,我想获取名称中包含“in”模式的国家/地区节点。

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
Run Code Online (Sandbox Code Playgroud)

我试过这个

    import xml.etree.ElementTree as ET
    tree = ET.parse('test.xml')
    root = tree.getroot()
    list=root.find(".//country[contains(@name, 'Pana')]")
Run Code Online (Sandbox Code Playgroud)

但我收到错误: SyntaxError: invalid predicate

有人可以帮忙解决这个问题吗?

har*_*r07 3

xml.etree.ElementTree仅对用于在树中定位元素的 XPath 表达式提供有限的支持,并且不包括 xpathcontains()函数。请参阅文档以获取支持的 xpath 语法列表。

您需要求助于提供更好 xpath 支持的库,例如lxml,或者使用更简单的 xpath 并手动进行进一步过滤,例如:

import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
list = filter(lambda x: 'Pana' in x.get('name'), root.findall(".//country[@name]"))
Run Code Online (Sandbox Code Playgroud)