简体   繁体   English

Python Elementtree删除/编辑节点

[英]Python Elementtree delete/edit a node

I am currently creating a project in python that requires xml manipulation. 我目前正在用python创建一个需要xml操作的项目。 To manipulate the xml file, I will use Elementtree. 要操纵xml文件,我将使用Elementtree。 Never worked with that module before. 以前从未使用过该模块。 I used to use php, but is complety different. 我曾经用过php,但是完全不同。

I have the following xml file: 我有以下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>

What I want to do is search by video title, (for exemple "name2") and then delete or edit that video entry. 我要做的是按视频标题搜索(例如“ name2”),然后删除或编辑该视频条目。 Exemples: Exemples:

1) Search for video with title "name2" and delete the video entry: 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) Search for video with title "name2" and edit that entry: 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>

Yes, it is possible to do that using ElementTree. 是的,可以使用ElementTree做到这一点。 The .remove() function can delete XML elements from an XML tree. .remove()函数可以从XML树中删除XML元素。 Here is an example of how to remove all videos named name2 from the XML file: 以下是如何从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')

Reference: 参考:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM