How to clone Element
objects in Python xml.etree
? I'm trying to procedurally move and copy (then modify their attributes) nodes.
views:
22answers:
2
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
2010-10-23 20:53:09
I think they do not copy the child nodes...
SHiNKiROU
2010-10-23 21:06:05
@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
2010-10-23 21:19:56
+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
2010-10-23 21:24:34