如何使用ElementT从Python中的XML文档中删除节点

2024-05-20 01:07:33 发布

您现在位置:Python中文网/ 问答频道 /正文

结构如下:

   <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")

Python2.7.1具有remove命令,但在remove时出现错误:

文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py”,第337行,在remove中 自身。移除(元素) 值错误:list.remove(x):x不在列表中

更新:

*由@martijn pieters求解-第二个for循环的正确逻辑是

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

Tags: nameinorgchildforfootagbar
1条回答
网友
1楼 · 发布于 2024-05-20 01:07:33

您需要从元素的中移除该元素;您需要直接获取对父元素的引用,尽管没有从子备份的路径。在本例中,您必须在查找<buildCommand>元素的同时获得对^{元素的引用。

尝试从根中删除标记失败,因为该标记不是根的直接子级。

相关问题 更多 >