如何使用ElementTree在Python中删除XML文档中的节点
这是结构:
<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 命令,但我在使用 remove 时遇到了错误:
文件 "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py",第 337 行,出错的地方是 remove self._children.remove(element) ValueError: list.remove(x): x not in list
更新:
* 这个问题是 @martijn-pieters 解决的 - 第二个 for 循环的正确逻辑是:
for tag in removeList:
parent = root.find('bar')
parent.remove(tag)
1 个回答
3
你需要把这个元素从它的父元素中移除;不过你得直接获取父元素的引用,因为从子元素是无法回到父元素的。在这种情况下,你需要在找到<buildCommand>
元素的同时,也获取<bar>
元素的引用。
尝试从根元素中移除这个标签会失败,因为这个标签并不是根元素的直接子元素。