Python etree 克隆节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4005975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
etree Clone Node
提问by Ming-Tang
How to clone Elementobjects in Python xml.etree? I'm trying to procedurally move and copy (then modify their attributes) nodes.
如何Element在 Python 中克隆对象xml.etree?我正在尝试按程序移动和复制(然后修改它们的属性)节点。
采纳答案by Steven
You can just use copy.deepcopy()to make a copy of the element. (this will also work with lxml by the way).
您可以只使用copy.deepcopy()来制作元素的副本。(顺便说一下,这也适用于 lxml)。
回答by Niel de Wet
If you have a handle on the Elementelem's parentyou can call
如果你有Elementelem's的句柄,parent你可以打电话
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.
但不建议这样做。
回答by Ali Afshar
A different, and somewhat disturbing solution:
一个不同的,有点令人不安的解决方案:
new_element = lxml.etree.fromstring(lxml.etree.tostring(elem))
回答by kitsu.eb
At least in Python 2.7 etree Element has a copy method: http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l233
至少在 Python 2.7 etree Element 有一个复制方法:http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py#l233
It is a shallow copy, but that is preferable in some cases.
这是一个浅拷贝,但在某些情况下更可取。
In my case I am duplicating some SVG Elements and adding a transform. Duplicating children wouldn't serve any purpose since where relevant they already inherit their parent's transform.
就我而言,我正在复制一些 SVG 元素并添加一个转换。复制孩子不会有任何用途,因为在相关的地方他们已经继承了他们父母的转变。
回答by DarkLighting
For future reference.
备查。
Simplest way to copy a node (or tree) and keep it's children, without having to import ANOTHERlibrary ONLYfor that:
复制节点(或树),并保持它的孩子,而无需导入最简单的方法ANOTHER库ONLY为:
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

