How to remove the current node, while iterating through all nodes from root by getiterator() function?
import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for node in root.getiterator():
#if some condition:
#remove(node)
解决方案
You can't remove nodes without knowing the parent, but the xml.etree package doesn't give you any way to access a parent from a given node.
The only way around this is matching the parent node instead:
for node in root.getiterator():
if some_condition_matches_parent:
for child in node.getiterator():
if some_condition_matches_child:
node.remove(child)
If you switch to the lxml library (which implements the same API, but with additional enhancements), you can retrieve the parent node from any given node:
node.getparent().remove(node)