这是结构:
<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(element) ValueError: list.remove (x): x 不在列表中
更新:
*由@martijn-pieters 解决 - 第二个 for 循环的正确逻辑是
for tag in removeList:
parent = root.find('bar')
parent.remove(tag)