I am trying to merge multiple XML files together using Python and no external libraries. The XML files have nested elements.
Sample File 1:
<root><element1>textA</element1><elements><nested1>text now</nested1></elements></root>
Sample File 2:
<root><element2>textB</element2><elements><nested1>text after</nested1><nested2>new text</nested2></elements></root>
What I Want:
<root><element1>textA</element1> <element2>textB</element2> <elements><nested1>text after</nested1><nested2>new text</nested2></elements> </root>
What I have tried:
From this answer.
from xml.etree import ElementTree as etdef combine_xml(files): first = None for filename in files: data = et.parse(filename).getroot() if first is None: first = data else: first.extend(data) if first is not None: return et.tostring(first)
What I Get:
<root><element1>textA</element1><elements><nested1>text now</nested1></elements><element2>textB</element2><elements><nested1>text after</nested1><nested2>new text</nested2></elements></root>
I hope you can see and understand my problem. I am looking for a proper solution, any guidance would be wonderful.
To clarify the problem, using the current solution that I have, nested elements are not merged.