无法使用ElementT删除元素/节点

2024-07-05 07:38:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我对ElementTree有个问题,我不太清楚。我已经阅读了他们的所有文档以及我在这个论坛上能找到的所有信息。我有几个元素/节点,我正试图删除使用ElementTree。下面的代码没有任何错误,但是当我查看编写更改的输出文件时,预期要删除的元素/节点仍然存在。我有一个文件如下所示:

<data>
  <config>
    <script filename="test1.txt"></script>
    <documentation filename="test2.txt"></script>
  </config>
</data>

我的代码如下所示:

import xml.etree.ElementTree as ElementTree    
xmlTree = ElementTree.parse(os.path.join(sourcePath, "test.xml"))
xmlRoot = xmlTree.getroot()
for doc in xmlRoot.findall('documentation'):
     xmlRoot.remove(doc)

xmlTree.write(os.path.join(sourcePath, "testTWO.xml"))

结果是我得到了以下文档:

<data>
  <config>
    <script filename="test1.txt" />
    <documentation filename="test2.txt" />
  </config>
</data>

我需要的是更像这样的东西。我没有被困在使用ElementTree。如果有一个更好的解决方案与lxml或其他一些图书馆,我洗耳恭听。我知道ElementTree有时会有点痛。你知道吗

<data>
  <config>
  </config>
</data>

Tags: 文件代码文档txtconfig元素data节点
1条回答
网友
1楼 · 发布于 2024-07-05 07:38:21

在代码中xmlRoot.findall('documentation')没有找到任何内容,因为<documentation>不是根元素<data>的直接子元素。它实际上是<config>的直接子级:

"Element.findall() finds only elements with a tag which are direct children of the current element". [19.7.1.3. Finding interesting elements]

这是一种可能的方法,可以使用findall()删除<config>的所有子元素,给定您发布的示例XML(并假设实际XML的<documentation>元素用正确的结束标记结束,而不是用</script>结束):

......
config = xmlRoot.find('config')

# find all children of config
for doc in config.findall('*'):
    config.remove(doc)
    # print just to make sure the element to be removed is correct
    print ElementTree.tostring(doc)
......

相关问题 更多 >