Python元素树删除/编辑节点

2024-10-02 20:41:25 发布

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

我目前正在用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”的视频并删除视频条目:

^{pr2}$

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>

Tags: 文件标题视频plottitlevideoanotheretc
1条回答
网友
1楼 · 发布于 2024-10-02 20:41:25

是的,使用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')

参考文献:

相关问题 更多 >