小编Abh*_*dra的帖子

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

我有这个 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

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

python xml xpath

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

python ×1

xml ×1

xpath ×1