我一直在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>
在某些情况下,我想删除subitem
s。在其他情况下,我想删除subsubitem
。我知道在当前给定的内容中我可以这样做:
只有当我知道目标节点的深度时,我才能以这种方式编写。如果我只知道要删除的节点的标记名,我应该如何实现它? 伪代码:
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
来解决这个问题。在
要删除}的实例,无论它们的深度如何,请考虑以下示例(注意它使用^{} 而不是上游ElementTree):
subsubitem
或{通过编写递归函数,我最终只在
xml
lib上完成了这项工作。在通过这样做,函数将迭代ET中的每个节点并删除我的目标节点。在
^{pr2}$希望这能帮助像我这样有限制要求的人。。。。在
相关问题 更多 >
编程相关推荐