![](/img/trans.png)
[英]How to delete a node from an XML document in Python using ElementTree
[英]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”),然后刪除或編輯該視頻條目。 Exemples:
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')
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.