使用ElementTree从XML中删除元素 [英] Remove element from XML with ElementTree

查看:372
本文介绍了使用ElementTree从XML中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可以打印出要删除的元素的名称:

I have the following code which prints out the name of the element I want to remove:

import xml.etree.ElementTree as ET

tree = ET.parse('myfile.xml')
root = tree.getroot()

for elem in tree.iter(tag='test'):
    print elem.tag

如何从中删除此元素我的XML?我的XML类似于以下内容:

How do I remove this element from my XML? My XML is similar to the following:

<foo>
   <bar>
      <level>
         <test name="1">
            <stuff>
               hello
            </stuff>
         </test>
         <test name="2">
            <stuff>
               hello
            </stuff>
         </test>
      </level>   
   </bar>
</foo>


推荐答案

根据提供的信息,您需要有指针到父标签以删除子标签。我已经相应地更新了您的代码。

Based on the information provided, you need to have pointer to parent tag in order to remove child tag. I have updated your code accordingly.

import xml.etree.ElementTree as ET

tree = ET.parse('myfile.xml')
root = tree.getroot()

for test in root.iter('test'):
    for stuff in test.findall('stuff'):
       test.remove(stuff)

print ET.tostring(root)

输出:

<foo>
   <bar>
      <level>
         <test name="1">
            </test>
         <test name="2">
            </test>
      </level>
   </bar>
</foo>

我希望这会有所帮助!

这篇关于使用ElementTree从XML中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆