[英]How to delete a node from an XML document in Python using 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 具有 remove 命令,但在刪除時出現錯誤:
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第 337 行,在刪除 self._children.remove(element) ValueError: list.remove (x): x 不在列表中
更新:
*由@martijn-pieters 解決 - 第二個 for 循環的正確邏輯是
for tag in removeList:
parent = root.find('bar')
parent.remove(tag)
您需要從其父元素中刪除該元素; 但是,您需要直接獲得對父級的引用,沒有從子級備份的路徑。 在這種情況下,您必須在查找<buildCommand>
元素的同時獲得對<bar>
元素的引用。
嘗試從根中刪除標簽失敗,因為該標簽不是根的直接子代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.