我的代码似乎得到了一个值错误,我不知道为什么。
ValueError: list.remove(x): x not in list
当我使用print语句时,我似乎正确地找到了日志设置,因为它打印了我希望看到的位置和数字。我不知道为什么我不能删除它。
XML
...
<security>
<rules>
<entry name="blah">
<log-setting> log-forwarding-main
这是我尝试的两个方法
import xml.etree.ElementTree as ET
tree = ET.parse('filelocation')
rules = tree.findall('.//security/rules/entry')
for rem_rule in rules:
log = rem_rule.findall('log-setting')
rem_rule.remove(log)
tree.write('newfilelocation')
并根据不同的帖子尝试了这个
import xml.etree.ElementTree as ET
tree = ET.parse('filelocation')
rules = tree.findall('.//security/rules/entry')
for rem_rule in rules[:]:
for rem_rule in rules[:]:
log = rem_rule.findall('log-setting')
rem_rule.remove(log)
tree.write('newfilelocation')
答案 0 :(得分:2)
根据文档xml.etree.ElementTree.Element
有一个函数.remove(subelement)
。但是,.findall()
将返回一个列表。因此,将rem_rule.remove(log)
替换为:
for element in log:
rem_rule.remove(element)
解决了这个问题。您的完整代码段看起来像
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
rules = tree.findall('.//security/rules/entry')
for rem_rule in rules:
log = rem_rule.findall('log-setting')
for element in log:
rem_rule.remove(element)
tree.write('newtest.xml')