我正在使用elementtree / lists编辑标签,在从配置标签获取信息后,我想删除标签。我尝试在i.remove(j)
下面这样做,如果我遍历列表列表,我可以看到确实删除了配置标记。但是当我写出文件时
他们还在那里,为什么会这样,我该怎么删除它们?是我正在编辑子列表然后将不同的列表写入文件吗?
import xml.etree.ElementTree as ET
ET.register_namespace("", "http://clish.sourceforge.net/XMLSchema")
tree = ET.parse('ethernet.xml')
root = tree.getroot()
command= ""
pattern = ""
operation = ""
priority= ""
action_command = """/klas/klish-scripts/ifrange.py run_command --cmdrange "${interface_method} ${iface_num} ${range_separator} ${iface_num2} ${range_separator2} ${interface_method2} ${iface_num3} ${range_separator3} ${iface_num4} ${range_separator4} ${interface_method3} ${iface_num5} ${range_separator5} ${iface_num6} ${range_separator6} ${interface_method4} ${iface_num7} ${range_separator7} ${iface_num8}" --command "%s" --klish_config "%s" --klish_action "%s" --priority "%s"
"""
commands = root.findall('{http://clish.sourceforge.net/XMLSchema}'
'VIEW/{http://clish.sourceforge.net/XMLSchema}COMMAND')
all1 = []
for command in commands:
all1.append(list(command.iter()))
atr = ""
for i in all1:
for j in i:
if "COMMAND" in j.tag:
if "name" in j.attrib:
pattern = j.attrib['name']
#print operation
if "CONFIG" in j.tag:
if "operation" in j.attrib:
operation = j.attrib['operation']
else:
operation = "set"
if "pattern" in j.attrib:
pattern = j.attrib['pattern']
if "priority" in j.attrib:
priority = j.attrib['priority']
else:
if operation == "unset":
priority = ""
else:
priority = "0x7f00"
atr = str(j.attrib)
**i.remove(j)**
if "ACTION" in j.tag:
if j.text:
command = j.text.strip()
j.text= action_command % (command, pattern, operation, priority)
else:
command = ""
cmd = ""
cmd += ifrange
for o in all1:
for y in o:
print y
**cmd += ET.tostring(o[0], encoding="utf-8", method="xml")**
cmd += end_tags
f = open('Z2.xml', 'w')
f.write(cmd)
f.close
编辑:解决方案,在我写入文件之前的文件末尾我将all1
重置为[]。然后我循环遍历树,删除必要的元素。
all1 = []
for command in commands:
for i in command:
#print i
if "CONFIG" in str(i):
command.remove(i)
all1.append(list(command.iter()))
答案 0 :(得分:1)
您只是从列表中删除对元素的引用。您需要在父元素上调用.remove()
。 ElementTree不保留父指针;仅给出一个CONFIG
元素,您就无法返回其父级的VIEW
元素。
这意味着您还需要保留对父级的引用。循环遍历VIEW
元素,然后在嵌套循环中找到要删除的CONFIG
元素,并且VIEW
父级仍然可用,请调用.remove()
删除子元素来自那个父母。