如何删除具有相同标记的最后一个同级节点?

2024-05-16 00:56:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我无法使用xml.etree.ElementTree文件. 我发现了类似的情况here,但这并不能解决我的问题。我也读过ElementTreeXPath的文档。你知道吗

我有一个类似这样的xml树

<metadata>
    <lineage>
        <srcinfo></srcinfo>
        <procstep>
            <otherinfo></otherinfo>
        </procstep>
        <procstep>
            <otherinfo></otherinfo>
        </procstep>
        <procstep>
            <otherinfo></otherinfo>
        </procstep>
        <procstep>
            <otherinfo></otherinfo>
        </procstep>
    </lineage>
</metadata>

假设我想删除第二、第三和第四步元素。我尝试了以下代码,结果是“ValueError:列表.删除(x) :x not in list“错误。你知道吗

while len(root.findall('.//lineage/procstep')) > 1:
        root.remove(root.findall('.//lineage/procstep[last()]'))

有没有什么建议来解释为什么这样做行不通?有没有其他办法解决我的问题?提前谢谢你的建议。你知道吗


Tags: 文件here情况rootxmlxpath建议lineage
1条回答
网友
1楼 · 发布于 2024-05-16 00:56:00

删除最后一步

要删除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)

相关问题 更多 >