gpt4 book ai didi

python - 从 etree 中删除一个节点但留下子节点

转载 作者:行者123 更新时间:2023-11-30 23:24:19 43 4
gpt4 key购买 nike

我正在遍历 XML 树,但从树中提取节点而留下其内部节点时遇到了一些麻烦。

例如:

<xml>
<letter name="B">
<letter name="D">
<letter name="E">
<letter name="F">
<letter name="G">

</letter>
</letter>
</letter>
</letter>
</letter>
</xml>

我需要这样的东西:

<xml>
<letter name="B">
<letter name="D">
<letter name="F">
<letter name="G">

</letter>
</letter>
</letter>
</letter>
</xml>

但是如果不删除所有 E 子级,我就无法得到这个。

干杯!

最佳答案

这个想法是找到带有 name="E", get it's parentletter 元素。 , remove the element从父级开始并用元素的子级扩展父级:

import xml.etree.ElementTree as etree

data = """
<xml>
<letter name="B">
<letter name="D">
<letter name="E">
<letter name="F">
<letter name="G">

</letter>
</letter>
</letter>
</letter>
</letter>
</xml>
"""

XPATH = './/letter[@name="E"]'

tree = etree.fromstring(data)
letter = tree.find(XPATH)
parent = tree.find(XPATH + '/..')

parent.remove(letter)
parent.extend(letter)

print etree.tostring(tree)

它打印:

<xml>
<letter name="B">
<letter name="D">
<letter name="F">
<letter name="G">

</letter>
</letter>
</letter>
</letter>
</xml>

UPD(使用迭代方法):

def iterparent(tree):
for parent in tree.getiterator():
for child in parent:
yield parent, child

tree = etree.fromstring(data)
for parent, child in iterparent(tree):
if child.tag == "letter" and child.attrib.get('name') == "E":
parent.remove(child)
parent.extend(child)

print etree.tostring(tree)

iterparent() 函数取自 Accessing Parents文档中的段落。

关于python - 从 etree 中删除一个节点但留下子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23498394/

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