从根目录删除元素时,Python ElementTree提供错误 [英] Python ElementTree gives Error when removing element from root

查看:66
本文介绍了从根目录删除元素时,Python ElementTree提供错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从xml文档中删除元素时出现以下错误。
ValueError:list.remove(x):x不在列表中
这是代码,该错误发生在带有remove的行上。

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.

使用ElementTree并非如此简单,在其上没有父指针要素。您需要先循环遍历转换,然后遍历

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)

我添加了一个额外的循环,该循环可查找所有具有至少一个类的 Transforms 元素元素。

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

如果要使用 lxml ,那么您可以使用 class2.getparent()。remove(class2)

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

这篇关于从根目录删除元素时,Python ElementTree提供错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆