How do I correctly remove a child xml tag with xml.etree ... | XML etree ElementTree clear
findallreturnanarray,thusyourchildisalsoanarray.Ifyouwanttoremoveallthechildren,youhavetomakeanotherloopforchildasforparentinroot.findall(parent):children=parent.findall(child)forchildinchildren:root.remove(child)Accordingtothe19.7.1.3.ofthexmlpackagedocs[1]Element.findall()findsonlyelementswithatagwhicharedirectchildrenofthecurrentelement.Element.find()findsthefirstchildwithaparticulartagThusifyouonlyhaveasinglechild,youcanusefindinsteadoffindall.thusthefollowingsnippedwouldthenbevalidforpa...
findall return an array, thus your child is also an array. If you want to remove all the children, you have to make another loop for child as
for parent in root.findall(parent): children = parent.findall(child) for child in children: root.remove(child)According to the 19.7.1.3. of the xml package docs[1]
Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag
Thus if you only have a single child, you can use find instead of findall. thus the following snipped would then be valid
for parent in root.find(parent): child = parent.find(child) parent.remove(child)Update with a fully working example with write to file what turns
import xml.etree.ElementTree as ET tree = ET.parse("test.xml") root = tree.getroot() for parent in root.findall(parent): children = parent.findall(child) for child in childre...