etree Clone Node

Viewed 30691

How to clone Element objects in Python xml.etree? I'm trying to procedurally move and copy (then modify their attributes) nodes.

7 Answers

If you procedurally move through your tree with loops, you can use insert to clone directly ( insert(index, subelement) ) and tree indexing (both in the documentation):

import xml.etree.ElementTree as ET
mytree = ET.parse('some_xml_file.xml')  # parse tree from xml file
root = mytree.getroot()  # get the tree root
    
for elem in root:  # iterate over children of root
   if condition_for_cloning(elem) == True:      
      elem.insert(len(elem), elem[3])  # insert the 4th child of elem to the end of the element (clone an element)  

or for children with some tag:

for elem in root:
   children_of_interest = elem.findall("tag_of_element_to_clone")
   elem.insert(len(elem), children_of_interest[1])

For anyone visiting from the future:

If you want to clone the entire element, use append.

new_tree = ET.Element('root')
for elem in a_different_tree:
    new_tree.append(elem)

@dennis-williamson made a comment about it which I overlooked and eventually stumbled on the answer here https://stackoverflow.com/a/6533808/4916945

Related