我正在使用xml.etree.Elementree
检索所有项目 <a>
至少有两个 child <b>
。我试图用 findall
来做到这一点方法,但似乎没有选项来检查此要求。
举个例子,如果我有这个文件:
<main>
<a>
<b>...</b>
<b>...</b>
</a>
<a>
<b>...</b>
</a>
<a>
<b>...</b>
<b>...</b>
<b>...</b>
<b>...</b>
</a>
</main>
我想检索第一个和第三个<a>
元素。
有没有办法执行此过滤?
最佳答案
使用lxml.etree.xpath()
方法:
from lxml import etree
tree = etree.parse('yourfile.xml')
nodes = tree.xpath('/main/a[count(./b) > 1]')
for a in nodes:
print(list(a)) # getting child nodes of the current <a> node
输出(连续:具有 2 个 b
子节点的 a
节点和具有 4 个 b
子节点的 a
节点) :
[<Element b at 0x1577d08>, <Element b at 0x1577d48>]
[<Element b at 0x1577d48>, <Element b at 0x1577d88>, <Element b at 0x1577dc8>, <Element b at 0x1577e08>]
关于python - 在 Python 中使用 xml.etree.Elementtree 检索至少具有两个特定类型子代的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47831096/