检索具有至少两个 children 特定类型且 xml.etree.Elementree in Python 的所有元素
Retrieving all elements with at least two children of specific type with xml.etree.Elementree in Python
我正在使用 xml.etree.Elementree
检索所有 <a>
至少有两个孩子 <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
输出(连续:a
节点有 2 个 b
个子节点和 a
节点有 4 个 b
个子节点:
[<Element b at 0x1577d08>, <Element b at 0x1577d48>]
[<Element b at 0x1577d48>, <Element b at 0x1577d88>, <Element b at 0x1577dc8>, <Element b at 0x1577e08>]
我正在使用 xml.etree.Elementree
检索所有 <a>
至少有两个孩子 <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
输出(连续:a
节点有 2 个 b
个子节点和 a
节点有 4 个 b
个子节点:
[<Element b at 0x1577d08>, <Element b at 0x1577d48>]
[<Element b at 0x1577d48>, <Element b at 0x1577d88>, <Element b at 0x1577dc8>, <Element b at 0x1577e08>]