2014-09-28 26 views
1

參考這個問題:Python: In an xml, How to delete nodes within a parent nodePython:爲什麼這個錯誤即將到來?

任何人都可以解釋我爲什麼我在我的Python腳本中面臨這個問題。

Value Error : list.remove(x): x not in list 

下面的代碼。

import xml.etree.cElementTree as ET 

try: 
    tree = ET.parse('Test.xml') 
    root = tree.getroot() 
    keeper_data = ['06354237', '87654321'] 
    instances = root.findall('./Replication/Instance') 
    for instance in instances: 
     data = instance.find('./DataSet/Data') 
     if data.text not in keeper_data: 
      root.remove(instance) 

tree.write('New.xml') 

except ValueError as err: 
    print ('Value Error : ' + str(err)) 

XML樣本。請到注意,從前面的問題XML結構,唯一的區別是增加了「複製」標籤的包圍所有的標籤。

<?xml version='1.0' encoding='UTF-8'?> 
<Root> 
<Identification> 
    <Description ID="12">Some text</Description> 
</Identification> 
<Symbols> 
    <Name Width="1">abc</Name> 
    <Name Width="2">def</Name> 
</Symbols> 
<Replication iRowRef="884"> 
    <Instance RowRef="A"> 
     <DataSet> 
      <Data>12345678</Data> 
     </DataSet> 
     <DataSet> 
      <Data>abcd</Data> 
     </DataSet> 
     <DataSet> 
      <Data>abcd</Data> 
     </DataSet> 
    </Instance> 
    <Instance RowRef="B"> 
     <DataSet> 
     <Data>87654321</Data> 
     </DataSet> 
     <DataSet> 
     <Data>abcd</Data> 
     </DataSet> 
     <DataSet> 
     <Data>abcd</Data> 
     </DataSet> 
    </Instance> 
    <Instance RowRef="C"> 
     <DataSet> 
     <Data>06354237</Data> 
     </DataSet> 
     <DataSet> 
     <Data>abcd</Data> 
     </DataSet> 
     <DataSet> 
     <Data>abcd</Data> 
     </DataSet> 
    </Instance> 
</Replication> 
</Root> 
+3

錯誤與您的代碼不符。另外,不要只將所有內容放在'try'塊中。這樣你就失去了重要的錯誤信息。刪除該塊,並將其放置在明確*想要捕捉某個錯誤的地方。 – poke 2014-09-28 12:37:43

+0

@poke你能解釋一下錯誤與我的代碼不匹配嗎?這實際上是我從我的程序中得到的輸出錯誤。 – manty 2014-09-28 12:40:59

+1

@poke,這實際上是確切的錯誤信息。它包含類型,而不是變量名稱,並將'x'作爲該項目的佔位符。試試'foo = []; foo.remove(「bar」)'和Python(3.3.5)會說'ValueError:list.remove(x):x not in list'。 – 2014-09-28 12:43:56

回答

2

你需要使用直接節點,根節點,而不是使用Element.remove

這裏我使用了lxml,因爲ElementTree沒有提供獲取父節點的方法。

import lxml.etree as ET 

tree = ET.parse('Test.xml') 
root = tree.getroot() 
keeper_data = ['06354237', '87654321'] 
instances = root.findall('./Replication/Instance') 
for instance in instances: 
    data = instance.find('./DataSet/Data') 
    if data.text not in keeper_data: 
     instance.getparent().remove(instance) 
...