我正在尝试从 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/