pythonxml删除孙子或孙辈

2024-09-22 16:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在google上搜索从xml文件中删除孙子。然而,我没有找到完美的解决办法。 这是我的案例:

<tree>
    <category title="Item 1">item 1 text
        <subitem title="subitem1">subitem1 text</subitem>
        <subitem title="subitem2">subitem2 text</subitem>
    </category>

    <category title="Item 2">item 2 text
        <subitem title="subitem21">subitem21 text</subitem>
        <subitem title="subitem22">subitem22 text</subitem>
            <subsubitem title="subsubitem211">subsubitem211 text</subsubitem>
    </category>
</tree>

在某些情况下,我想删除subitems。在其他情况下,我想删除subsubitem。我知道在当前给定的内容中我可以这样做:

^{pr2}$

只有当我知道目标节点的深度时,我才能以这种方式编写。如果我只知道要删除的节点的标记名,我应该如何实现它? 伪代码:

import xml.etree.ElementTree as ET

for item in root.getiterator():
    if item.tag == 'subsubitem' or item.tag == 'subitem':
        # remove item

如果我做root.remove(item),它肯定会返回一个错误,因为项不是root的直接子项。在

编辑时间: 我不能安装任何第三方库,所以我必须用xml来解决这个问题。在


Tags: texttreetitlerootxmlitemcategorysubitem
2条回答

要删除subsubitem或{}的实例,无论它们的深度如何,请考虑以下示例(注意它使用^{}而不是上游ElementTree):

import lxml.etree as etree

el = etree.fromstring('<root><item><subitem><subsubitem/></subitem></item></root>')
for child in el.xpath('.//subsubitem | .//subitem'):
  child.getparent().remove(child)

通过编写递归函数,我最终只在xmllib上完成了这项工作。在

def recursive_xml(root):
    if root.getchildren() is not None:
        for child in root.getchildren():
            if child.tag == 'subitem' or child.tag == 'subsubitem':
                root.remove(child)
            else:
                recursive_xml(child)

通过这样做,函数将迭代ET中的每个节点并删除我的目标节点。在

^{pr2}$

希望这能帮助像我这样有限制要求的人。。。。在

相关问题 更多 >