【问题标题】:XPath: Find all known tags with specific attribute [duplicate]XPath:查找具有特定属性的所有已知标签[重复]
【发布时间】:2018-04-29 20:20:25
【问题描述】:

我想使用 Python 从以下 XML 获取所有带有 attr 属性(但不是 xxx 或任何其他)的 trololo 标记的列表:

<data>
    <test>
        <trololo attr="1">
        </trololo>
    </test>
    <test>
        <trololo>
        </trololo>
    </test>
    <test>
        <trololo attr="X">
        </trololo>
    </test>
    <test>
        <xxx attr="Y">
        </xxx>
    </test>
</data>

我尝试过使用//*[@attr],但结果也包含xxx 标签。到目前为止,我尝试的所有其他变体都失败了。

我正在使用的实际 Python 代码:

import xml.etree.ElementTree as ET
from pprint import pprint

tree  = ET.parse('test.xml')
nodes = tree.findall('//*trololo[@attr]')

pprint(nodes)

输出:

[]

更新:

我发现这是一个命名空间问题,这使得这个问题成为duplicate。问题是我的根节点看起来像这样:

<data xmlns="http://example.com">

【问题讨论】:

  • 请注意,我不知道&lt;trololo&gt; 节点的实际深度。它们可能比 root 低 100 级。
  • 你用的是哪个python版本?
  • 我已经从我的终端运行了同样的,我得到了输出[&lt;Element 'trololo' at 0x7fab55c90ef8&gt;, &lt;Element 'trololo' at 0x7fab55c903b8&gt;]
  • @FarhanK 我正在使用 Python 3。
  • nodes = tree.findall('//trololo[@attr]') 即没有*?

标签: python xml xpath


【解决方案1】:

具有命名属性的名称的所有元素

作为@har07 correctly answers in the comments,XPath

//trololo[@attr]

将根据请求选择所有具有attr 属性(无论其值如何)的trololo 元素。

这个字符串,

//*trololo[@attr]

在语法上根本不是 XPath 表达式,但确实很相似,

//*:trololo[@attr]

在 XPath 2.0(但不是 XPath 1.0)下语法无效。它说要在任何命名空间中选择 trololol 元素。要忽略 XPath 1.0 (but you really shouldn't) 中的命名空间,请使用 local-name()

//*[local-name() = 'trololo' and @attr]

其他变体

  • 所有具有命名属性的元素: //*[@attr]
  • 具有任意属性的所有元素: //*[@*]

【讨论】:

  • 我发现这确实是命名空间问题。谢谢!
猜你喜欢
  • 2011-04-16
  • 1970-01-01
  • 2013-01-04
  • 2016-11-13
  • 2021-06-25
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
相关资源
最近更新 更多