带有 xml.etree.ElementTree : multiple conditions 的 Python xpath

标签 python xml python-3.x xpath

我正在尝试从 XML 文件中计算以下形式的所有 XML 节点:

....
<node id="0">
      <data key="d0">Attribute</data>
....
</node>
....

例如这样的文件:

<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">

  <graph edgedefault="directed">
    <node id="0">
      <data key="d0">Attribute</data>
      <data key="d1">Foo</data>
    </node>

我试过的是:

x = graphml_root.findall(".//"+nsfy("node")+"/["+nsfy("data")+"='Attribute']")

但他只说 XML 的文本必须是“Attribute”,我想确保“Attribute”是带有 key="d0" 的节点的文本,所以我试过这个:

x = graphml_root.findall(".//"+nsfy("node")+"/"+nsfy("data")+"[@key='d0']"+"[""'Attribute']")

但它返回一个空列表,所以我遗漏了一些东西。

注意: 我不得不写一点 lambda 来避免一直复制 xmlnamespace:

nsfy = lambda x : '{http://graphml.graphdrawing.org/xmlns}'+x #to be able to read namespace tags

谢谢。

最佳答案

尝试做类似的事情:

nodes = []
containers = graphml_root.findall('.//node/data[@key="d0"]')
for container in containers:
    if container.text == "Attribute":
        nodes.append(container)

count = len(nodes)

关于带有 xml.etree.ElementTree : multiple conditions 的 Python xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45005730/

相关文章:

python-3.x - 高效找到一定范围内的素数

python - 如何使用 FitsIO 更新 FITS 文件头?

python - 在Python中选择和迭代多维数组中的特定子数组

android - ViewPager pageSelected 无法正常工作

python - 绕过 dok_matrix.get 类型检查

c# - 指示 XmlWriterSettings 使用自闭合标签

xml - 如何为 XAML 创建我自己的(非 CLR!)XML 命名空间?

python - 方法需要 'double *' 类型的参数?

python - Django:类型错误:实例(模型对象)之间不支持 '<'

php - 如何在php上运行python?