I want to remove a specific element with all sub element which belongs to him. to find the element I want to remove I'm want to use the id of tag or the name of the tag.
For example, given this etree object
<?xml version="1.0" ?>
<root>
<tag_folders>
<folder id="1">Stars</folder>
<folder id="2">Planet</folder>
<folder id="3">Satellite</folder>
</tag_folders>
<tags>
<tag>
<name>Earth</name>
</tag>
<tag id="2">
<name>Sun</name>
</tag>
<tag id="29">
<name>Moon</name>
</tag>
</tags>
</root>
for example I want to remove Moon with the id "29"
the output I want :
<?xml version="1.0" ?>
<root>
<tag_folders>
<folder id="1">Stars</folder>
<folder id="2">Planet</folder>
<folder id="3">Satellite</folder>
</tag_folders>
<tags>
<tag>
<name>Earth</name>
</tag>
<tag id="2">
<name>Sun</name>
</tag>
</tags>
</root>
Here is my code :
def remove_tag(root, tag_id_r):
i = 0
for tag in root.iter('tag'):
tag_id = tag.get('id')
if (tag_id == tag_id_r):
#root.clear(tag)
#root.remove(tag)
#root[1][i].remove(tag)
# print(i, tag_id, tag_id_r, root[1][i])
i += 1
def main():
with open("lib.xml", 'a') as f:
tree = etree.parse('lib.xml')
root = tree.getroot()
remove_tag(root, input("What is the id of the tag you want to remove?"))
f.seek(0)
f.truncate()
dom = minidom.parseString(etree.tostring(tree, encoding="utf-8"))
print('\n'.join([line for line in dom.toprettyxml(indent=' '*2).split('\n') if line.strip()]), file=f)
main()
I tried everything in the comments but it doesn't work