繁体   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