title: Python xml duplicate a specific sub element and all sub elements and change its name
body: <p>I built a full root tree with subelements from an xml and just need to duplicate a certain part with a name change before writing to the file, example</p>
  <p>I tried using deepcopy but no luck.</p>
  <p>example:</p>
  <pre><code>   &lt;main ....&gt;
       &lt;head ....&gt;
        &lt;element 1 .... &gt;
           &lt;sub1 xxx&gt;
              &lt;sub1.2 xxxx&gt;
                 &lt;sub1.2.1&gt;
                    &lt;sub1.2.1.1&gt;
                    &lt;/sub1.2.1.1&gt;
                 &lt;sub1.2.2&gt;
                 &lt;/sub1.2.2&gt;
                  .
                  .
                  .
        &lt;element_1/&gt;
       &lt;/head&gt;
      &lt;/main&gt;
      
      
  </code></pre>
  <p>The new root should look like</p>
  <pre><code> &lt;main ....&gt;
   &lt;head ....&gt;
    &lt;element_1 .... &gt;
       &lt;sub1 xxx&gt;
          &lt;sub1.2 xxxx&gt;
             &lt;sub1.2.1&gt;
                &lt;sub1.2.1.1&gt;
                &lt;/sub1.2.1.1&gt;
             &lt;sub1.2.2&gt;
             &lt;/sub1.2.2&gt;
              .
              .
              .
    &lt;element_1/&gt;
  </code></pre>
  <p>The new root should look like below after copy:</p>
  <pre><code>  &lt;new_copy_element .... &gt;  #same data below as the one in element_1
       &lt;sub1 xxx&gt;
          &lt;sub1.2 xxxx&gt;
             &lt;sub1.2.1&gt;
                &lt;sub1.2.1.1&gt;
                &lt;/sub1.2.1.1&gt;
             &lt;sub1.2.2&gt;
             &lt;/sub1.2.2&gt;
              .
              .
              .
    &lt;new_copy_element/&gt;
   &lt;/head&gt;
  &lt;/main&gt;
  </code></pre>
  <p>current code before cloning something like:</p>
  <pre><code>parser = etree.XMLParser(remove_blank_text=True)
  tree = etree.parse(input_filename, parser)
  root = tree.getroot()
  
  ####    
  for elem in root.getiterator():
      if not hasattr(elem.tag, 'find'): continue  # (1)
      i = elem.tag.find('}')
      if i &gt;= 0:
          elem.tag = elem.tag[i+1:]
  objectify.deannotate(root, cleanup_namespaces=True)
  
  
  def write_xml(file, element):
      xmlstr = minidom.parseString(ET.tostring(element)).toprettyxml(indent=&quot;  &quot;)
      with open(file, &quot;w&quot;) as f:
          f.write(xmlstr)
          f.close()   
      
      
      
  head = SubElement(root, 'head')
  
  
  elem1 = SubElement(head, 'element_1')
  
  elem1.set('xx', xx)
  sub1 = SubElement(elem1, 'sub1')
  sub1.set('xxx', &quot;yyy&quot;)
  
  
  for key, value in data.items():
      sub11 = SubElement(sub1, 'sub1.1')
      sub11.set('nnn', str(key))
      .
      .     
  elem2 = SubElement(elem1, 'elem2')
  
  .
  .
  
  write_xml(output_filename,root)
  </code></pre>
  <p>(I need to duplicate all data from elem1 but names it element_2 for example before or after I call write_xml</p>