pythonxmlmergeelementtree

How to merge two xml files at a specific level


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>

Solution

  • 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')