Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何从xml中删除列表中不存在的子节点_Python 3.x_Xml_Xml.etree - Fatal编程技术网

Python 3.x 如何从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

我有一个具有不同数量节点级别的xml。我想检查树中的每个节点,并仅当它及其子节点不在列表中时将其删除

<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)
在此之后,以root
elements\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>