xml - Python Elementtree delete/edit a node -
i creating project in python requires xml manipulation. manipulate xml file, use elementtree. never worked module before. used use php, complety different.
i have 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 want search video title, (for exemple "name2") , delete or edit video entry. exemples:
1) search video title "name2" , delete 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 video title "name2" , edit 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, possible using elementtree. .remove() function can delete xml elements xml tree. here example of how remove videos named name2 xml file:
import xml.etree.elementtree et tree = et.parse('in.xml') root = tree.getroot() items_to_delete = root.findall("./video[title='name2']") item in items_to_delete: root.remove(item) tree.write('out.xml') reference:
Comments
Post a Comment