【问题标题】:Find XML attribute "NOT equal to" in Python在 Python 中查找 XML 属性“不等于”
【发布时间】:2023-03-07 13:06:01
【问题描述】:

我有以下 XML:

<foo>
<bar x="0"/>
<bar x="1"/>
</foo>

我提前知道这里会有两个子元素,一个的 x 为 0,而另一个的 x 为 I-don't-know-what。我想选择属性值不为 0 的子元素。我假设你会这样做:

foo.find("bar[@x!='0']")

但这不会返回任何东西。根据下面的链接,我尝试了以下操作,但出现了错误。

foo.find("bar[not(@x='0')]")

Python lxml.html XPath "attribute not equal" operator not working as expected

【问题讨论】:

    标签: python xml lxml


    【解决方案1】:

    您是否尝试将 .find 替换为 .xpath() 您问题中的链接使用 xpath。

    from lxml import etree
    path=r"C:\foo.xml"
    tree = etree.parse(path)
    
    print tree.xpath('bar[not(@x="0")]')
    

    【讨论】:

    • 是的,做到了。谢谢!
    猜你喜欢
    • 2021-05-18
    • 2015-06-01
    • 1970-01-01
    • 2016-12-28
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多