[英]Remove element and children from XML with elementtree Python
現在嘗試了幾種不同的庫,並認為即時消息很接近,但無法找出此問題。
我有一個XML文件,其中包含一些要刪除的嵌套表。 這些是XML層次結構中的幾個層次。
到目前為止,我已經嘗試過了...
import xml.etree.ElementTree as ET
import os
tree = ET.parse('/Users/me/file.xml')
root = tree.getroot()
for sect1 in root.findall('section1'):
for sect2 in sect1.iter() :
if sect2.tag == 'table':
sect1.remove(sect2)
但是我得到了錯誤:
ValueError: list.remove(x): x not in list
我可以使用以下代碼從層次結構的頂層成功刪除文檔的各個部分:
import xml.etree.ElementTree as ET
import os
tree = ET.parse('/Users/me/file.xml')
root = tree.getroot()
for sect1 in root.findall('section1'):
root.remove(sect1)
我只是想念如何從頂層刪除更遠的元素。
任何幫助,不勝感激。
我使用minidom解析xml文件和字符串,使用minidom可以輕松地執行所需的任何操作,這是您請求的示例,但使用xml.dom.minidom
庫:-
from xml.dom.minidom import parse
doc = parse('/Users/me/file.xml')
root = doc.documentElement
for parent in root.childNodes:
for child in parent.childNodes:
if(child.tagName == 'table'):
parent.removeChild(child)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.