简体   繁体   中英

Python Elementtree delete/edit a node

I am currently creating a project in python that requires xml manipulation. To manipulate the xml file, I will use Elementtree. Never worked with that module before. I used to use php, but is complety different.

I have the following xml file:

<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. Exemples:

1) Search for video with title "name2" and delete the video entry:

<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:

<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. The .remove() function can delete XML elements from an XML tree. Here is an example of how to remove all videos named name2 from the XML file:

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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