ElementTree and clone element toot

m.banaouas banaouas.medialog at wanadoo.fr
Mon Feb 2 11:21:29 EST 2009


My python version is 2.4.4

def SubElement(parent, tag, attrib={}, **extra):

Can you tell me how does "parent" issue could be solved by SubElement ?
I'm looking for how to determine element parent just by asking element it self.
It seems like element doesn't know witch is its parent, while any parent knows
well witch are its childs.

My goal is to clone an element and attach it to a specified parent or to parant
of original element to clone.

may be better implementation of CloneElement is to let the caller context make
the attachement between the clone and its parent.

Gabriel Genellina a écrit :
> 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, and you also should use the SubElement
> factory instead of makeelement as documented; doing that fixes the
> "parent" issue too.
> 



More information about the Python-list mailing list