gpt4 book ai didi

python XML : get direct child nodes

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:38 24 4
gpt4 key购买 nike

我有一个如下所示的 xml。我想获取Node1下的所有直接子节点。我正在尝试使用 childNodes,但是,它也返回 Node21 和 Node22。我怎样才能得到那些直接的子节点

<Node1>
<Node11>
<Node21>
</Node21>
<Node22>
</Node22>
<Node23>
</Node23>
</Node11>
<Node12>
</Node12>
<Node13>
</Node13>
</Node1>

更新对困惑感到抱歉。我弄错了,好像只获取到直接子节点。但是,item number is the childnodes 仍然超过了真正的子节点。我尝试获取节点名称。我收到很多“#text”

最佳答案

xml.ElementTree.Element 支持迭代器协议(protocol),因此您可以按如下方式使用list(elem):

import xml.etree.cElementTree as ET

s = '''
<Node1>
<Node11>
<Node21>
</Node21>
<Node22>
</Node22>
<Node23>
</Node23>
</Node11>
<Node12>
</Node12>
<Node13>
</Node13>
</Node1>
'''

root = ET.fromstring(s)

print root
print list(root)

关于 python XML : get direct child nodes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11840036/

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