如何使用Python删除元素节点,但将其子节点保留在XML文件中?

如何使用Python删除元素节点,但将其子节点保留在XML文件中?,python,xml,Python,Xml,我对Python和XML世界有点陌生。我非常需要你的帮助,我快没时间完成这个项目了!基本上,我有一个xml文件,在将其导入Excel之前需要详细说明。我的XML结构如下(非常小的摘录): 我需要做的是解析xml文件(elementtree或lxml),并消除和,以获得如下内容: <?xml version="1.0" encoding="UTF-8"?> <Application> <third/> <third/&g

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


我需要做的是解析xml文件(elementtree或lxml),并消除
,以获得如下内容:

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

我已经阅读并尝试了我能找到的所有相关问题,但我所能做到的只是消除了整个
元素

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


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

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

1)加载XML(并将这里考虑的节点设为“应用程序”)

2) 获取树的内部节点列表(树->节点->内部节点)

3) 获取所有内部节点(此处名称为“third”的节点)

4) 删除root-“application”的直接子级

5) 将所有内部节点附加到根节点

yourxmlfile.txt

<?xml version="1.0" encoding="UTF-8"?>\n<Application>\n    <first/>\n    <second>\n        <third/>\n        <third/>\n        <third/>\n    </second>\n</Application>
\n\n\n\n\n\n\n\n\n
您可以使用e tree.parse()读取xml文件

>将xml.etree.ElementTree导入为etree
>>>root=etree.parse('yourxmlfile.xml')
>>>etree.tostring(根目录)
b'\n\n\n\n\n\n\n\n'
>>>内部节点=[node.getchildren()中的节点的node.getchildren()
>>>打印(内部节点)
[[], [, ]]
>>>对于root.getchildren()中的节点:root.remove(节点)
... 
>>>etree.tostring(根目录)
b'\n'
>>>[[root.append(c)for c in child]for child in filter(无,内部_节点)]
[[无,无,无]]
>>>etree.tostring(根目录)
b'\n\n\n\n'

欢迎来到SO。请看一看。您可能还需要检查、和以及如何创建。张贴您尝试过的代码和收到的错误。尽可能具体,因为这将导致更好的答案。向我们展示除了所需的xml之外您正在使用的代码谢谢@ABDUL NIYAS P M,但我已经尝试过了。我遇到的问题是,我需要解析xml文件,无法在python脚本中手动复制它。你有什么建议?换句话说,如何将“with open…as…”与您链接的解决方案中显示的代码结合起来?@Luke您可以这样读取xml文件。“将xml.etree.ElementTree导入为ET tree=ET.parse('your_xml_file.xml')”@Luke您可以从字符串和文件中解析xml。谢谢你的意见,但它不起作用。你知道怎么做而不把它变成字符串吗?除了打印,我不会在其他任何地方把它变成字符串。我已经使用了etree.parse()!你能分享你得到的错误回溯吗?
<?xml version="1.0" encoding="UTF-8"?>\n<Application>\n    <first/>\n    <second>\n        <third/>\n        <third/>\n        <third/>\n    </second>\n</Application>
>>> 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>'