Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

etree Clone Node

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

like image 360
Ming-Tang Avatar asked Oct 23 '10 20:10

Ming-Tang


People also ask

What is Etree in LXML?

lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.

What does Etree parse do?

etree. ElementTree module and Minidom (Minimal DOM Implementation). Parsing means to read information from a file and split it into pieces by identifying parts of that particular XML file.


2 Answers

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

like image 114
Steven Avatar answered Oct 02 '22 00:10

Steven


A different, and somewhat disturbing solution:

new_element = lxml.etree.fromstring(lxml.etree.tostring(elem)) 
like image 22
Ali Afshar Avatar answered Oct 02 '22 00:10

Ali Afshar