Scott C Wilson
Scott C Wilson

Reputation: 20016

How to delete a node from an XML document in Python using ElementTree

Here's the structure:

   <foo>
        <bar> 
    <buildCommand>
        <name>com.android.ide.eclipse.adt.ApkBuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
    <buildCommand>
        <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
        <triggers>auto,full,incremental,</triggers>
    </buildCommand>
        </bar>
   </foo>

and here's my logic, which identifies the buildCommand I want to delete (the second one), adds it to a list, and then does a remove.

import os;
import xml.etree.ElementTree as ET

document = ET.parse("foo"); 
root = document.getroot(); 
removeList = list()
for child in root.iter('buildCommand'): 
   if (child.tag == 'buildCommand'): 
      name = child.find('name').text
      if (name == 'org.eclipse.ui.externaltools.ExternalToolBuilder'):
          removeList.append(child)

for tag in removeList:
   root.remove(tag)

document.write("newfoo")

Python 2.7.1 has the remove command but I get an error on remove:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 337, in remove self._children.remove(element) ValueError: list.remove(x): x not in list

UPDATE:

* Solved by @martijn-pieters - correct logic for second for loop is

for tag in removeList:
   parent = root.find('bar')
   parent.remove(tag)

Upvotes: 2

Views: 11246

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

You need to remove the element from its parent; you'll need to get a reference to the parent directly though, there is no path from child back up. In this case you'll have to get a reference to the <bar> element at the same time as finding the <buildCommand> element.

Trying to remove the tag from the root fails because the tag is not a direct child of the root.

Upvotes: 3

Related Questions