1

I'm getting the following error when attempting to remove an element from the xml document. "ValueError: list.remove(x): x not in list" Here is the code, the error occurs on the line with the remove.

import xml.etree.ElementTree as ET
tree = ET.parse("AddInClasses.xml")
rootElem = tree.getroot()
for class2 in rootElem.findall("Transforms/class"):
    name2 = class2.find("name")
    if name2.text == "Get Field":
        rootElem.remove(class2)
tree.write("AddInClassesTrimmed.xml")
Derick
  • 311
  • 4
  • 5

2 Answers2

12

You are looping over elements that are not direct children of the root. You'll need to get a reference to the direct parent instead.

With ElementTree that is not that easy, there are no parent pointers on the elements. You'll need to loop over Transforms first, then over class:

for parent in rootElem.findall("Transforms[class]"):
    for class2 in parent.findall("class"):
        name2 = class2.find("name")
        if name2.text == "Get Field":
            parent.remove(class2)

I added an extra loop that finds all Transforms elements that have at least one class element contained in them.

If you were to use lxml instead, then you could just use class2.getparent().remove(class2).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Ahh Thank you Sir @MartijnPieters as I have been searching all day for this! I was trying to use ElementTree. I just switched to lxml to use getparent() and it worked like a charm. Dear lord I purged this xml that was over 300K lines long, and took out all of these unnecessary tags and now have a clean 5000 lines of XML. Much cleaner to read and easier to work with. Upvoted, repped, TU, etc. – drez90 Apr 14 '14 at 18:59
0

following also should work...

    import xml.etree.ElementTree as ET
    tree = ET.parse("AddInClasses.xml")
    rootElem = tree.getroot()
    for class2 in rootElem.findall("Transforms/class"):
        name2 = class2.find("name")
        if name2.text == "Get Field":
           rootElem.find("Transforms").remove(class2) #<<< see the lone change here
    tree.write("AddInClassesTrimmed.xml")
towers
  • 1