views:

22

answers:

2

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

A: 

If you have a handle on the Element elem's parent you can call

new_element = SubElement(parent, elem.tag, elem.attrib)

Otherwise you might want to try

new_element = makeelement(elem.tag, elem.attrib)

but this is not advised.

nieldw
I think they do not copy the child nodes...
SHiNKiROU
@SHiNKiROU You can compare `id(old_element)` with `id(new_element)` to see if it actually creates a different object in memory. Does this help?
nieldw
+1  A: 

You can just use copy.deepcopy() to make a copy of the element. (this will also work with lxml by the way).

Steven