如何在python中连接两个xml文件



使用Python模块import xml.etree.ElementTree,如何连接两个文件?假设每个文件都被写入磁盘,而不是硬编码。作为Linux环境的一个例子,cat被用来打印每个文件的内容。

[lt;user/path>]$cat file1.xml

<file>has_content</file>

[lt;user/path>]$cat file2.xml

<root>more_content</root>

打开每个文件并连接到第一个之后

[lt;user/path>]$cat new_file.xml

<new_root><file>has_content</file><root><more_content</root></new_root>

我想简单地将这两个文件"合并"在一起,但我一直在努力。我所能找到的只是附加到一个子元素或添加一个子元素。

你能试试这个并检查你的需求是否得到满足吗。我使用模块xml.etree.ElementTree获取文件file1、file2的XML数据,然后将内容附加到一个新文件中,根节点为

<new_root>
...
</new_root>

代码:

import xml.etree.ElementTree as ET
data1 = ET.tostring(ET.parse('file1.xml').getroot()).decode("utf-8")
data2 = ET.tostring(ET.parse('file2.xml').getroot()).decode("utf-8")
f = open("new_file.xml", "a+")
f.write('<new_root>')
f.write(data1)
f.write(data2)
f.write('</new_root>')
f.close()

最新更新