我有以下代码打印出我要删除的元素的名称:
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类似于以下内容:
<foo>
<bar>
<level>
<test name="1">
<stuff>
hello
</stuff>
</test>
<test name="2">
<stuff>
hello
</stuff>
</test>
</level>
</bar>
</foo>
答案 0 :(得分:2)
根据提供的信息,您需要具有指向父标记的指针才能删除子标记。我已相应更新了您的代码。
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>
我希望这有帮助!