Python 3.x 如何从xml中删除列表中不存在的子节点
我有一个具有不同数量节点级别的xml。我想检查树中的每个节点,并仅当它及其子节点不在列表中时将其删除Python 3.x 如何从xml中删除列表中不存在的子节点,python-3.x,xml,xml.etree,Python 3.x,Xml,Xml.etree,我有一个具有不同数量节点级别的xml。我想检查树中的每个节点,并仅当它及其子节点不在列表中时将其删除 <node1> <xxx> stuff </xxx> <subnode2> <yyy> stuf2 </yyy> </subnode2> </node1> 您可以检查元素是否应该重复删除—如果它至少包含一个“不可移动”子元素,则不应该 d
<node1>
<xxx>
stuff
</xxx>
<subnode2>
<yyy>
stuf2
</yyy>
</subnode2>
</node1>
您可以检查元素是否应该重复删除—如果它至少包含一个“不可移动”子元素,则不应该
dontRemove = ['xxx','yyy']
elements_to_remove = []
def should_not_be_removed(parent):
if parent.tag in dontRemove:
return True
nonremovable_child_found = False
for child in parent:
if should_not_be_removed(child):
nonremovable_child_found = True
if not nonremovable_child_found:
elements_to_remove.append(parent)
return nonremovable_child_found
should_not_be_removed(root)
在此之后,以rootelements\u to\u remove开始的重复调用包含一个元素列表,其中不包含在dont remove
我还扩展了xml以涵盖更多的测试用例,请检查这是否是您的意思:
<node1>
<xxx>
don't remove
</xxx>
<subnode2>
<yyy>
don't remove
</yyy>
</subnode2>
<subnode3>
remove
</subnode3>
<subnode4>
<xxx>
don't remove
</xxx>
<abc>
remove
</abc>
</subnode4>
</node1>
不要移除
不要移除
去除
不要移除
去除
您的问题还不清楚:规则是什么?如果不删除标记,但也不应删除标记及其所有祖先(一直到根),是的,对不起。我想检查树中的每个标记,只有当它及其子项不在列表中时才将其删除。因此,当节点有两个子项时,一个子项在“不删除”列表中,另一个子项不在列表中,哪些被删除,哪些保留?因此不应删除“不删除”列表中的父项和子项。应删除第二个子项(如果列表中没有该子项)。
<node1>
<xxx>
don't remove
</xxx>
<subnode2>
<yyy>
don't remove
</yyy>
</subnode2>
<subnode3>
remove
</subnode3>
<subnode4>
<xxx>
don't remove
</xxx>
<abc>
remove
</abc>
</subnode4>
</node1>