[英]How do I correctly remove a child xml tag with xml.etree.elementtree?
我正在嘗試從 xml 文件中刪除所有子標簽,同時保持父標簽不變。 我曾嘗試遍歷元素以制作一個列表並以這種方式刪除它們,但是 elementtree 模塊不喜歡那樣。
import xml.etree.ElementTree as ET
tree = ET.parse("myfile")
root = tree.getroot()
for parent in root.find('parent'):
child = parent.findall('child')
#print(len(child))
root.remove(child)
tree.write("myfile")
我將打印函數散列出來,以表明我可以在那里看到列表的正確長度。
remove 調用返回錯誤
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
我哪里錯了? 我是否過度簡化了 ElementTree 刪除的工作方式?
findall
返回一個數組,因此您的child
也是一個數組。 如果你想刪除所有的孩子,你必須為child
做另一個循環
for parent in root.findall('parent'):
children = parent.findall('child')
for child in children:
root.remove(child)
Element.findall() 僅查找帶有標記的元素,這些元素是當前元素的直接子元素。 Element.find() 查找具有特定標簽的第一個孩子
因此,如果您只有一個孩子,則可以使用find
而不是findall
。 因此,以下剪輯將是有效的
for parent in root.find('parent'):
child = parent.find('child')
parent.remove(child)
更新一個完整工作的例子,寫到文件什么變成
import xml.etree.ElementTree as ET
tree = ET.parse("test.xml")
root = tree.getroot()
for parent in root.findall('parent'):
children = parent.findall('child')
for child in children:
parent.remove(child)
tree.write("test1.xml")
這個片段會變成
<foo>
<parent>
<child>
<grandchild>
</grandchild>
</child>
<child>
<grandchild>
</grandchild>
</child>
<child>
<grandchild>
</grandchild>
</child>
</parent>
...
</foo>
進入
<foo>
<parent>
</parent>
...
</foo>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.