2013-07-08 27 views
0

我正在編輯具有elementtree/lists的標籤,並且在從配置標籤獲取信息後,我想要刪除該標籤。我試着在i.remove(j)的下面這樣做,如果我遍歷列表的列表,我可以看到那個配置標籤確實被刪除了。但是,當我寫出文件 他們仍然存在,爲什麼是這樣的,我該如何刪除它們?是我在編輯一個子列表,然後寫一個不同的列表到文件?從elementtree/list中刪除元素

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

回答

1

您只刪除對列表中元素的引用。您需要改爲在父元素上調用.remove()。 ElementTree不保留父指針;如果單獨給出CONFIG元素,則無法返回作爲其父項的VIEW元素。

這意味着您還需要保留對父級的引用。遍歷VIEW元素,然後在嵌套循環中找到要刪除的CONFIG元素,並且VIEW父級仍然可用,請致電.remove()從該父級中刪除子元素。

+0

我在我骯髒的解決方案中編輯過,但我會考慮如何使它更好地與您的答案,謝謝。 – Paul