【问题标题】:How to remove element node but keep its childs in a XML file using Python?如何使用 Python 删除元素节点但将其子节点保留在 XML 文件中?
【发布时间】:2017-10-26 15:53:27
【问题描述】:

我对 Python 和 XML 世界有点陌生。我非常需要你的帮助,我没时间完成这个项目了!基本上我有一个 xml 文件,我需要在将其导入 Excel 之前对其进行详细说明。我的 XML 结构如下(非常小的摘录):

<?xml version="1.0" encoding="UTF-8"?>
<Application>
    <first/>
    <second>
        <third/>
        <third/>
        <third/>
    </second>
</Application>

我需要做的是解析xml文件(elementtree或lxml)并消除&lt;first/&gt;&lt;second/&gt;,以获得这样的东西:

<?xml version="1.0" encoding="UTF-8"?>
<Application>
        <third/>
        <third/>
        <third/>      
</Application>

我已经阅读并尝试了我能找到的所有相关问题,但我设法实现的只是消除整个 &lt;first/&gt; 元素。

我使用的是 Python 3.6.2,首选标准库(lxml、elementtree)。

提前感谢您提供的任何帮助!

【问题讨论】:

  • 欢迎来到 SO。请查看tour。您可能还想查看What topics can I ask aboutHow to Ask,以及如何创建minimal reproducible example。发布您尝试过的代码和您收到的错误。尽可能具体,因为它会导致更好的答案。除了您需要的 xml 之外,向我们展示您正在使用的代码
  • 谢谢@ABDUL NIYAS P M,但我已经尝试过了。我遇到的问题是我需要解析 xml 文件,我无法手动将其复制到 python 脚本中。你有什么建议?换句话说,如何将“with open ... as ...”与您链接的解决方案中显示的代码结合起来?
  • @Luke 你可以像这样读取 xml 文件。 "将 xml.etree.ElementTree 导入为 ET 树 = ET.parse('your_xml_file.xml')"
  • @Luke 您可以从字符串和文件中解析 xml。 more info

标签: python xml


【解决方案1】:

最终任务是删除给定示例中的父节点。(应用程序 - 根,第一个,第二个 - 节点,第三个内部节点) )

1) 加载您的 xml(并在此处找到您认为是“应用程序”的节点)

2) 获取你的树的 inner_nodes(tree->nodes->inner_nodes) 列表

3) 获取所有的inner_nodes(此处名为'third'的节点)

4) 删除根的直接子级 - 'Applicaiton'

5) 将所有 inner_nodes 附加到您的根目录!

你的xml文件.txt

<?xml version="1.0" encoding="UTF-8"?>\n<Application>\n    <first/>\n    <second>\n        <third/>\n        <third/>\n        <third/>\n    </second>\n</Application>

您可以使用 tree.parse() 读取您的 xml 文件

>>> import xml.etree.ElementTree as etree
>>> root=etree.parse('yourxmlfile.xml')
>>> etree.tostring(root)
b'<Application>\n    <first />\n    <second>\n        <third />\n        <third />\n        <third />\n    </second>\n</Application>'
>>> inner_nodes=[node.getchildren() for node in root.getchildren()]
>>> print(inner_nodes)
[[], [<Element 'third' at 0x10c272818>, <Element 'third' at 0x10c2727c8>, <Element 'third' at 0x10c272778>]]
>>> for node in root.getchildren():root.remove(node)
... 
>>> etree.tostring(root)
b'<Application>\n    </Application>'
>>> [[root.append(c) for c in child] for child in filter(None,inner_nodes)]
[[None, None, None]]
>>> etree.tostring(root)
b'<Application>\n    <third />\n        <third />\n        <third />\n    </Application>'

【讨论】:

  • 感谢您的意见,但它不起作用。你知道如何在不把它变成字符串的情况下做到这一点吗?
  • 除了打印之外,我不会在其他任何地方将其设为字符串。我用过 etree.parse() !你能分享你得到的错误的回溯吗?
猜你喜欢
  • 2022-12-13
  • 2021-06-11
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 2018-06-18
  • 2023-03-11
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多