Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from XML with ElementTree

I have the following code which prints out the name of the element I want to remove:

import xml.etree.ElementTree as ET

tree = ET.parse('myfile.xml')
root = tree.getroot()

for elem in tree.iter(tag='test'):
    print elem.tag

How do I remove this element from my XML? My XML is similar to the following:

<foo>
   <bar>
      <level>
         <test name="1">
            <stuff>
               hello
            </stuff>
         </test>
         <test name="2">
            <stuff>
               hello
            </stuff>
         </test>
      </level>   
   </bar>
</foo>
like image 661
Proletariat Avatar asked Dec 04 '25 18:12

Proletariat


1 Answers

Based on the information provided, you need to have pointer to parent tag in order to remove child tag. I have updated your code accordingly.

import xml.etree.ElementTree as ET

tree = ET.parse('myfile.xml')
root = tree.getroot()

for test in root.iter('test'):
    for stuff in test.findall('stuff'):
       test.remove(stuff)

print ET.tostring(root)

Output:

<foo>
   <bar>
      <level>
         <test name="1">
            </test>
         <test name="2">
            </test>
      </level>
   </bar>
</foo>

I hope this helps!

like image 181
Vedant Parikh Avatar answered Dec 06 '25 08:12

Vedant Parikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!