Python : Copy entire node along with sub nodes in XML
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
import copy
<b>
<c>
<d>India</d>
</c>
<c>
<d>USA</d>
</c>
<c>
<d>China</d>
</c>
</b>
</a>"""
#---------------------
def xml_node_grabber(xml , node_name):
result=[]
xml_tree = ElementTree.fromstring(xml)
for i in xml_tree.findall(".//"+node_name):
dupe = copy.deepcopy(i) #copy <c> node
result.append(dupe) #insert the new node
iterator_res=iter(result)
return (iterator_res)
#------------------------
res=xml_node_grabber(xml, "c")
for i in res:
print(ElementTree.tostring(i))
Result:
b'<c>\n <d>USA</d>\n </c>\n '
b'<c>\n <d>China</d>\n </c>\n