ElementTree and clone element toot

Gerard Flanagan grflanagan at gmail.com
Mon Feb 2 10:52:59 EST 2009


Gabriel Genellina wrote:
> En Mon, 02 Feb 2009 12:37:36 -0200, Gerard Flanagan 
> <grflanagan at gmail.com> escribió:
> 
>> e = ET.fromstring(s)
>>
>> def clone(elem):
>>      ret = elem.makeelement(elem.tag, elem.attrib)
>>      ret.text = elem.text
>>      for child in elem:
>>          ret.append(clone(child))
>>      return ret
>>
>> f = clone(e)
> 
> You forget the tail attribute, 

I did, thanks.

and you also should use the SubElement
> factory instead of makeelement as documented; doing that fixes the 
> "parent" issue too.
> 

I suppose I would have just used the Element factory if the OP hadn't 
otherwise:

def clone(elem):
     ret = ET.Element(elem.tag, elem.attrib)
     ret.text = elem.text
     ret.tail = elem.tail
     for child in elem:
         ret.append(clone(child))
     return ret

Not sure what SubElement gains you, in the context of the above function?




More information about the Python-list mailing list