Remove element from XML with ElementTree

只愿长相守 提交于 2020-03-23 08:08:11

问题


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

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>

回答1:


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)

Output:

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

I hope this helps!



来源:https://stackoverflow.com/questions/47041688/remove-element-from-xml-with-elementtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!