ElementTree and clone element toot

m.banaouas banaouas.medialog at wanadoo.fr
Mon Feb 2 10:46:41 CET 2009

Hi all,
Working with the ElementTree module, I looked for clone element function but not
found such tool:

def CloneElment(fromElem, destRoot = None)
fromElem is the element to clone
destRoot is the parent element of the new element ; if None so the new element
will be child of fromElem parent. The clone operation is recursive to make it
process all subtree of the element to clone.

here is my first implementation:

def CloneElement(fromElem, destRoot = None):
  if destRoot == None:
    fromRoot = ET.ElementTree(fromElem).getroot()
    destRoot = fromRoot
  destElem = destRoot.makeelement(fromElem.tag, fromElem.attrib)
  destElem.text = fromElem.text
  for e in fromElem.findall('*'):
    CloneElement(e, destElem)
this function works fine only if destRoot parameter is defined by the caller
context. The problem is about retreiving parent element: I didn't found any way
to determine the parent element of an element "elem" by asking elem itself!
and ET.ElementTree(fromElem).getroot() is wrong because it returns fromElem
itself, not its parent.

Thanks for any help.

More information about the Python-list mailing list