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>

1 Answer 1

11

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.