【发布时间】: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">
【问题讨论】:
-
请注意,我不知道
<trololo>节点的实际深度。它们可能比 root 低 100 级。 -
你用的是哪个python版本?
-
我已经从我的终端运行了同样的,我得到了输出
[<Element 'trololo' at 0x7fab55c90ef8>, <Element 'trololo' at 0x7fab55c903b8>] -
@FarhanK 我正在使用 Python 3。
-
nodes = tree.findall('//trololo[@attr]')即没有*?