2

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>
Proletariat
  • 213
  • 5
  • 10

1 Answers1

10

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!

Vedant Parikh
  • 218
  • 2
  • 8