gpt4 book ai didi

python - 使用 elementtree Python 从 XML 中删除元素和子元素

转载 作者:行者123 更新时间:2023-12-01 09:00:08 25 4
gpt4 key购买 nike

现在尝试了几个不同的库,我认为我很接近,但无法解决这个问题。

我有一个 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"]' 选择具有特定属性的元素如果您想了解更多信息,这称为 xpath,元素树提供的精简版本已记录在 here 中。

关于python - 使用 elementtree Python 从 XML 中删除元素和子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com