2013-03-23 27 views
1

這裏刪除一個節點的結構:如何從XML文檔中使用Python的ElementTree

<foo> 
     <bar> 
    <buildCommand> 
     <name>com.android.ide.eclipse.adt.ApkBuilder</name> 
     <arguments> 
     </arguments> 
    </buildCommand> 
    <buildCommand> 
     <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name> 
     <triggers>auto,full,incremental,</triggers> 
    </buildCommand> 
     </bar> 
    </foo> 

,這裏是我的邏輯,它標識buildCommand我想刪除(第二個),其添加到列表,然後刪除。

import os; 
import xml.etree.ElementTree as ET 

document = ET.parse("foo"); 
root = document.getroot(); 
removeList = list() 
for child in root.iter('buildCommand'): 
    if (child.tag == 'buildCommand'): 
     name = child.find('name').text 
     if (name == 'org.eclipse.ui.externaltools.ExternalToolBuilder'): 
      removeList.append(child) 

for tag in removeList: 
    root.remove(tag) 

document.write("newfoo") 

的Python 2.7.1具有去除命令,但我得到刪除錯誤:

文件「/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ XML/etree/ElementTree.py」,管線337,在刪除 self._children.remove(元件) ValueError異常:list.remove(X):X不在列表中

UPDATE:

*由@ martijn-pi解決ETERS - 對於第二個for循環正確的邏輯是

for tag in removeList: 
    parent = root.find('bar') 
    parent.remove(tag) 

回答

3

您需要從它的父刪除元素;你需要直接得到父對象的引用,但是沒有從孩子備份的路徑。在這種情況下,您必須在找到<buildCommand>元素的同時獲取對<bar>元素的引用。

試圖從根中刪除標記失敗,因爲標記不是根的直接子項。

+0

謝謝!更新了問題以顯示您的答案。這是做這種「XML編輯」最pythonic的方式,還是我應該使用另一種方法,如構建一個並行文檔,並排除該節點? –

+1

我改用'lxml'代替;它支持相同的API,但增加了更好的XPath支持以及對節點父節點的訪問。 –

+0

我現在還沒有走過lxml的路線,因爲我在Mac OSX 10.7上,它沒有lxml - 這裏是想要在該平臺上使用lxml的人們的想法:http://stackoverflow.com/questions/ 7961577 /需要幫助安裝lxml-on-os-x-10-7 –

相關問題