etree Clone Node

2019-02-07 17:51发布

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

5条回答
该账号已被封号
2楼-- · 2019-02-07 18:10

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

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.

查看更多
Lonely孤独者°
3楼-- · 2019-02-07 18:13

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

查看更多
劫难
4楼-- · 2019-02-07 18:17

A different, and somewhat disturbing solution:

new_element = lxml.etree.fromstring(lxml.etree.tostring(elem))
查看更多
冷血范
5楼-- · 2019-02-07 18:23

For future reference.

Simplest way to copy a node (or tree) and keep it's children, without having to import ANOTHER library ONLY for that:

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
查看更多
做自己的国王
6楼-- · 2019-02-07 18:26

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.

查看更多
登录 后发表回答