python - 在 Python 中使用 xml.etree.Elementtree 检索至少具有两个特定类型子代的所有元素

标签 python xml elementtree

我正在使用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/

相关文章:

从 tesseract 导入 image_to_string 时出现 Python 错误

python - 如何创建一个包含子元素的列表(Python 元素树)

python - pip 10 没有名为 pip.req 的模块

python - Google Cloud Storage 的 URLFetch 速率限制

xml - 通过 augeas 添加属性到 XML 根节点时出现问题

java - 在 Android 中映射 XML 属性和代码方法

java - 创建 RSS 源 XML 文件时出错 - Java

Python XML ElementTree 标记通配符

python - 元素树 : Can't build root tree when getting XML from webpage

python - 为什么 re 模块试图导入 enum.IntFlag?