Python Elementtree delete/edit 一个节点

Python Elementtree delete/edit a node

我目前正在 python 中创建一个需要 xml 操作的项目。要操作 xml 文件,我将使用 Elementtree。以前从未使用过该模块。我曾经使用 php,但完全不同。

我有以下 xml 文件:

<myvideos>
    <video>
        <title>video1</title>
        <plot>description bla bla bla</plot>
        <duration>50</duration>
    </video>
    <video>
        <title>name2</title>
        <plot>another description bla bla bla</plot>
        <duration>37</duration>
    </video>
    <video>
        <title>another name etc</title>
        <plot>description etc...</plot>
        <duration>99</duration>
    </video>
</myvideos>

我想做的是按视频标题搜索(例如 "name2"),然后删除或编辑该视频条目。 例子:

1) 搜索标题为 "name2" 的视频并删除视频条目:

<myvideos>
    <video>
        <title>video1</title>
        <plot>description bla bla bla</plot>
        <duration>50</duration>
    </video>
    <video>
        <title>another name etc</title>
        <plot>description etc...</plot>
        <duration>99</duration>
    </video>
</myvideos>

2) 搜索标题为 "name2" 的视频并编辑该条目:

<myvideos>
    <video>
        <title>video1</title>
        <plot>description bla bla bla</plot>
        <duration>50</duration>
    </video>
    <video>
        <title>name2renamed</title>
        <plot>edited</plot>
        <duration>9999</duration>
    </video>
    <video>
        <title>another name etc</title>
        <plot>description etc...</plot>
        <duration>99</duration>
    </video>
</myvideos>

是的,使用 ElementTree 可以做到这一点。 .remove() 函数可以从 XML 树中删除 XML 个元素。以下是如何从 XML 文件中删除所有名为 name2 的视频的示例:

import xml.etree.ElementTree as ET
tree = ET.parse('in.xml')
root = tree.getroot()

items_to_delete = root.findall("./video[title='name2']")
for item in items_to_delete:
    root.remove(item)

tree.write('out.xml')

参考: