I want to merge two xml files using Python:
File1.xml
<?xml version='1.0' encoding='ASCII'?>
<MyData>
<Elements>
<Element>
<ElementID>15</ElementID>
</Element>
</Elements>
</MyData>
And File2.xml
<?xml version='1.0' encoding='ASCII'?>
<MyData>
<Elements>
<Element>
<ElementID>16</ElementID>
</Element>
</Elements>
</MyData>
I can use the approach suggested in this Medium post:
import xml.etree.ElementTree as ET
tree1 = ET.parse('File1.xml')
tree2 = ET.parse('File2.xml')
root1 = tree1.getroot()
root2 = tree2.getroot()
root1.extend(root2)
tree1.write('merged_files.xml')
This returns:
<MyData>
<Elements>
<Element>
<ElementID>15</ElementID>
</Element>
</Elements>
<Elements>
<Element>
<ElementID>16</ElementID>
</Element>
</Elements>
</MyData>
But how can I merge files at a given “level”, e.g. Elements?
I would like to obtain:
<MyData>
<Elements>
<Element>
<ElementID>15</ElementID>
</Element>
<Element>
<ElementID>16</ElementID>
</Element>
</Elements>
</MyData>
5
Extending Elements
on first file with all Element
from second file
root1 = tree1.getroot()
root2 = tree2.getroot()
root1.find('Elements').extend(root2.findall(".//Element"))
tree1.write('merged_files.xml')
1
I have found a method that is finding Elements tag of first xml and append the all children of the second xml Elements‘s data to it
import xml.etree.ElementTree as ET
first_tree = ET.parse('File1.xml')
first_root = first_tree.getroot()
second_tree = ET.parse('File2.xml')
second_root = second_tree.getroot()
first_elements = first_root.find('Elements')
second_elements = second_root.find('Elements')
"""Merges the 'Elements' nodes from two XML files into a single XML file.
This code iterates through the 'Elements'
nodes in the second XML file and appends them to the 'Elements' in
the first XML file. It then writes the merged
XML tree to a new file named 'MergedFile.xml'."""
for elem in second_elements:
first_elements.append(elem)
first_tree.write('MergedFile.xml', encoding='ASCII',
xml_declaration=True)
merged_tree = ET.ElementTree(first_root)
ET.dump(merged_tree)
I’ll hope this would be helpful
2