40

如何Element在 Python 中克隆对象xml.etree?我正在尝试按程序移动和复制(然后修改它们的属性)节点。

4

6 回答 6

53

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

于 2010-10-23T21:24:34.247 回答
14

一个不同的,有点令人不安的解决方案:

new_element = lxml.etree.fromstring(lxml.etree.tostring(elem))
于 2012-11-20T01:14:19.503 回答
1

至少在 Python 2.7 etree Element 有一个复制方法: http ://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l233

这是一个浅拷贝,但在某些情况下更可取。

就我而言,我正在复制一些 SVG 元素并添加一个变换。复制孩子不会有任何目的,因为他们已经继承了他们父母的变换。

于 2013-05-28T19:31:16.363 回答
0

如果您有Element elem's的句柄,parent您可以致电

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

否则你可能想试试

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

但不建议这样做。

于 2010-10-23T20:53:09.707 回答
0

如果您使用循环程序在树中移动,则可以使用insert直接克隆(insert(index, subelement))和树索引(都在文档中):

import xml.etree.ElementTree as ET
mytree = ET.parse('some_xml_file.xml')  # parse tree from xml file
root = mytree.getroot()  # get the tree root
    
for elem in root:  # iterate over children of root
   if condition_for_cloning(elem) == True:      
      elem.insert(len(elem), elem[3])  # insert the 4th child of elem to the end of the element (clone an element)  

或者对于有一些标签的孩子:

for elem in root:
   children_of_interest = elem.findall("tag_of_element_to_clone")
   elem.insert(len(elem), children_of_interest[1])
于 2021-08-04T17:44:30.410 回答
-2

备查。

复制节点(或树)并保留其子节点的最简单方法,而无需为此导入另一个库:

def copy_tree( tree_root ):
    return et.ElementTree( tree_root );

duplicated_node_tree = copy_tree ( node );    # type(duplicated_node_tree) is ElementTree
duplicated_tree_root_element = new_tree.getroot();  # type(duplicated_tree_root_element) is Element
于 2014-11-24T16:28:11.967 回答