遍历 GraphML (XML) 文件并提取所有值

Iterating through a GraphML (XML) file and extracting all the values

我有一个 XML(实际上是 GraphML)文件,如下所示:

<?xml version="1.0" ?>
<graphml>
    <key attr.name="label" attr.type="string" id="label"/>
    <graph edgedefault="directed" id="">
        <node id="0">
            <type>p</type>
            <label>sshd(3,2)</label>
        </node>
        <node id="1">
            <type>e</type>
            <label>user(3)</label>
        </node> 
    </graph>
</graphml>

我想遍历这个并提取每个单独的项目(打印它)。在普通的 XML 文件中,这是相当简单的,但在这种情况下,我似乎无法做到这一点。这是我正在使用的代码。

tree = ET.parse(FILENAME)
    root=tree.getroot()
    for child in root:
        for x in child:
            NodeType =  child.find('node').find('type')
            LabelType = child.find('node').find('label')
            print(NodeType.text, LabelType.text)

这给我的是前两个值重复两次,换句话说:

p  sshd(3,2)
p  sshd(3,2)

而不是:

p  sshd(3,2)
e  user(3)

有人可以帮忙吗?

x 从未在嵌套循环中使用

for child in root:
    for x in child:

您可以一次指定从根到 node 个元素的确切路径:

for node in root.findall('graph/node'):
    print(node.find('type').text, node.find('label').text)

eval.in demo