簡體   English   中英

使用elementtree Python從XML中刪除元素和子元素

[英]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)

我只是想念如何從頂層刪除更遠的元素。

任何幫助,不勝感激。

用這個:

for sect1 in root.findall('.//section1'):
root.remove(sect1)

.//從第一個元素的所有子section1元素中選擇。 您可以更具體地選擇帶有'./section1/section2'元素,也可以通過./section1[@Name="SomeValueForNameAttribute"]' './section1/section2'選擇具有特定屬性的元素,如果您想知道更多的信息,稱為xpath, 此處記錄元素樹提供的簡化版本

我使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM