This is very similar to this question: Insert XML document into existing XML with Python, but I need to be able to insert many different xml documents with many attributes into deeply nested portions of an existing XML document where the subelements have the same name. Here is a MWE without attributes to clutter things up
The main document I need to insert elements into:
<a><b1><array><c1></c1><c1></c1><c1></c1></array></b1><b2></b2></a>
The XML I want to insert:
<f><g><h2></h2><h1></h1></g></f>
The output I want:
<a>
<b1>
<array>
<c1 />
<c1>
<f>
<g>
<h2 />
<h1 />
</g>
</f>
</c1>
<c1 />
</array>
</b1>
<b2 />
</a>
My current python code:
import xml.etree.ElementTree as ET
top_xml = ET.fromstring("<a><b1><array><c1></c1></array></b1><b2></b2></a>")
bottom_xml = ET.fromstring("<f><g><h2></h2><h1></h1></g></f>")
#want to insert `bottom_xml` under the <c1> tag
here is where I get stuck. ElementTree.insert and ElementTree.append appear to work on the top element. Ive seen other answers using ElementTree.subelement to add simple xml elements to subelements, but manually recreating the xml structure of bottom_xml when it could be hundreds of lines deep seems to be unwieldy.