Reputation: 33
My code seems to be getting a value error and I am not sure why.
ValueError: list.remove(x): x not in list
When I use a print statement I seem to find the log setting correctly because it prints the location and number I would expect to see. I am just not sure why I can't remove it.
XML
...
<security>
<rules>
<entry name="blah">
<log-setting> log-forwarding-main
And here is the two scipts I have tried
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')
And tried this per a different post
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')
Upvotes: 1
Views: 677
Reputation: 553
According to the documentation xml.etree.ElementTree.Element
has a function .remove(subelement)
. However, .findall()
will return a list. Thus, replacing rem_rule.remove(log)
with:
for element in log:
rem_rule.remove(element)
solves the problem. Your complete snippet then looks like
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')
Upvotes: 2