0

我无法使用 xml.etree.ElementTree 删除某些元素。我在这里发现了类似的情况,但它并没有解决我的问题。我还阅读了有关ElementTreeXPath的文档。

我有一个类似的 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()]'))

关于为什么这不起作用的任何建议?还有其他方法可以解决我的问题吗?提前感谢您的任何建议。

4

1 回答 1

0

删除最后一个 procstep

要删除procstep元素,请使用 procstep 的父级 ( lineage)。

尝试:

lineage = root.find('.//lineage')
last_procstep = lineage.find('./procstep[last()]')
lineage.remove(last_procstep)

如果你使用 lxml,你可以使用getparent()如下:

last_procstep = root.find('.//lineage/procstep[last()]')
last_procstep.getparent().remove(last_procstep)

删除 procstep 元素但第一个

lineage = root.find('.//lineage')
for procstep in tuple(lineage.iterfind('./procstep'))[1:]:
    lineage.remove(procstep)
于 2013-08-09T17:07:47.273 回答