【问题标题】:How to search for a Xml node with a given attribute value in python如何在python中搜索具有给定属性值的Xml节点
【发布时间】:2015-04-21 12:54:59
【问题描述】:

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

我试过了

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

但我收到一个错误:SyntaxError: invalid predicate

谁能帮忙解决这个问题?

【问题讨论】:

    标签: python xml xpath


    【解决方案1】:

    xml.etree.ElementTree对用于在树中定位元素的 XPath 表达式提供有限支持,并且不包括 xpath contains() 函数。有关支持的 xpath 语法列表,请参阅 the documentation

    您需要求助于提供更好 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]"))
    

    【讨论】:

    • 谢谢。您提供的解决方案正在运行。有没有办法进行不区分大小写的搜索?
    • @AbhishekMoondra 您可以更改lambda 以在比较之前将属性值转换为更低:lambda x: 'pana' in x.get('name').lower()。这将导致不区分大小写的搜索..
    【解决方案2】:

    我无法评论为什么您的原始代码不起作用,但它与 XPath 表达式无关。表达式很好,除了前面的 . 可以安全地省略。

    您不使用lxml xpath() method的任何原因?

    from lxml import etree
    tree = etree.parse('etree.xml')
    root = tree.getroot()
    list = root.xpath("//country[contains(@name,'Pana')]")
    
    print list[0].tag
    

    返回一个country 元素:

    $ python test.py
    country
    

    【讨论】:

      【解决方案3】:

      您使用的 xml 解析器不支持contains。您将需要使用不同的解析器来获得完整的 xpath 支持

      https://docs.python.org/2/library/xml.etree.elementtree.html#elementtree-xpath

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多