Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Using the Python module import xml.etree.ElementTree , how can I concatenate two files? Assuming each file is written to disk and NOT hard coded in. As an illustration of the Linux environment, cat is being used to print the contents of each of these files.

[<user/path>]$ cat file1.xml

<file>has_content</file>

[<user/path>]$ cat file2.xml

<root>more_content</root>

After each of the files has been opened and concatenated to the first

[<user/path>]$ cat new_file.xml

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

I would like to simply 'merge' these two files together but I have been struggling. All I have been really able to find is about appending to a child or adding a SubElement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
296 views
Welcome To Ask or Share your Answers For Others

1 Answer

Could you try this and check whether your requirement is satisfied. I have used the module xml.etree.ElementTree for getting the XML data of files file1, file2 and then appended the contents to a new file with the root node being

<new_root>
...
</new_root>

Code:

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...