简体   繁体   中英

Python ElementTree gives Error when removing element from root

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM