gpt4 book ai didi

python - 我只想要 XML 元素的直接子元素,而不是所有后代

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:36 25 4
gpt4 key购买 nike

我有一个表示有向图的 XML 文档。它包含大量直接子级,所有子级都有 id,以及大量嵌套子级,所有子级都具有相同的标签名称,但没有 id,只有引用。

我想迭代根节点的所有直接子节点,但排除嵌套子节点。这些文件看起来像这样,但有数百个节点和数十个不同的标签:

<graph>
<foo id="f1"><bar ref="b1" /><baz ref="z1" />...</foo>
<bar id="b1"><foo ref="f1" /></bar>
<baz id="z1"></baz>
...
</graph>

我不想使用 getElementsByTagName 因为它返回所有后代。我怀疑我需要使用 .childnodes 并过滤结果,但我想确保没有遗漏的东西。

此外,我无法控制输入,它来自外部源,并且我正在使用 Python 的 xml.dom.minidom 模块,但我希望这是一个实现细节。

最佳答案

不太确定您想从受指导的 child 那里得到什么,所以给了您一些不同的例子。

from lxml import etree

root = etree.fromstring(xml)

for node in root.iter("graph"):
#To get the namespaces of the direct children
namespaces = [child.namespace for child in node]

#To get the tags of the direct children
tags = [child.tag for child in node]

#To get the text of the direct children
texts = [child.text for child in node]

关于python - 我只想要 XML 元素的直接子元素,而不是所有后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30466039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com