【发布时间】:2013-08-09 16:57:02
【问题描述】:
我无法使用 xml.etree.ElementTree 删除某些元素。我发现了类似的情况here,但这并不能解决我的问题。我还阅读了ElementTree 和XPath 上的文档。
我有一个类似的 xml 树
<metadata>
<lineage>
<srcinfo></srcinfo>
<procstep>
<otherinfo></otherinfo>
</procstep>
<procstep>
<otherinfo></otherinfo>
</procstep>
<procstep>
<otherinfo></otherinfo>
</procstep>
<procstep>
<otherinfo></otherinfo>
</procstep>
</lineage>
</metadata>
假设我想删除第二个、第三个和第四个 procstep 元素。我尝试了以下代码,结果出现“ValueError:list.remove(x):x not in list”错误。
while len(root.findall('.//lineage/procstep')) > 1:
root.remove(root.findall('.//lineage/procstep[last()]'))
关于为什么这不起作用的任何建议?还有其他方法可以解决我的问题吗?提前感谢您的任何建议。
【问题讨论】:
标签: python xml xpath elementtree