我无法使用 xml.etree.ElementTree 删除某些元素。我在这里发现了类似的情况,但它并没有解决我的问题。我还阅读了有关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()]'))
关于为什么这不起作用的任何建议?还有其他方法可以解决我的问题吗?提前感谢您的任何建议。