繁体   English   中英

如何使用 xml.etree.elementtree 正确删除子 xml 标记?

[英]How do I correctly remove a child xml tag with xml.etree.elementtree?

我正在尝试从 xml 文件中删除所有子标签,同时保持父标签不变。 我曾尝试遍历元素以制作一个列表并以这种方式删除它们,但是 elementtree 模块不喜欢那样。

import xml.etree.ElementTree as ET    

tree = ET.parse("myfile")
root = tree.getroot()

for parent in root.find('parent'):
    child = parent.findall('child')
    #print(len(child))
    root.remove(child)

tree.write("myfile")

我将打印函数散列出来,以表明我可以在那里看到列表的正确长度。

remove 调用返回错误

TypeError: remove() argument must be xml.etree.ElementTree.Element, not list

我哪里错了? 我是否过度简化了 ElementTree 删除的工作方式?

findall返回一个数组,因此您的child也是一个数组。 如果你想删除所有的孩子,你必须为child做另一个循环

for parent in root.findall('parent'):
    children = parent.findall('child')
    for child in children:
        root.remove(child)

根据19.7.1.3。xml 包文档

Element.findall() 仅查找带有标记的元素,这些元素是当前元素的直接子元素。 Element.find() 查找具有特定标签的第一个孩子

因此,如果您只有一个孩子,则可以使用find而不是findall 因此,以下剪辑将是有效的

for parent in root.find('parent'):
    child = parent.find('child')
    parent.remove(child)

更新一个完整工作的例子,写到文件什么变成

import xml.etree.ElementTree as ET    

tree = ET.parse("test.xml")
root = tree.getroot()

for parent in root.findall('parent'):
    children = parent.findall('child')
    for child in children:
        parent.remove(child)
tree.write("test1.xml")

这个片段会变成

<foo>
    <parent>
        <child>
            <grandchild>
            </grandchild>
        </child>
        <child>
            <grandchild>
            </grandchild>
        </child>
        <child>
            <grandchild>
            </grandchild>
        </child>
    </parent>
    ...
</foo>

进入

<foo>
    <parent>
        </parent>
    ...
</foo>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM