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")

2 Answers 2

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).

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

1 Comment

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 <msg></msg> tags and now have a clean 5000 lines of XML. Much cleaner to read and easier to work with. Upvoted, repped, TU, etc.
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")

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.