简体   繁体   English

Python ElementTree - 插入元素的副本

[英]Python ElementTree - Inserting a copy of an element

I have the following xml code: 我有以下xml代码:

<data factor="1" name="ini" value="342" />

I want to copy the same information, but with a different name. 我想复制相同的信息,但名称不同。 ie, The final output should be: 即,最终输出应为:

<data factor="1" name="ini" value="342" />
<data factor="1" name="raw_ini" value="342" />

I tried to do the following: 我试着做以下事情:

model_tag = tree.findall(data_path) #I make sure that data_path is correct.
len_tags = len(model_tag)
i = 0
while i < len_tags: 
    tipo_tag = model_tag[i]
    if tipo_tag.attrib['name']=='ini':
        aux_tag = copy.deepcopy(tipo_tag) #I tried also with copy.copy(tipo_tag).
        aux_tag.attrib['name'] = 'raw_ini'
        model_tag.append(aux_tag)

tree.write(dir_output) 

If I use "copy.deepcopy" I don't have an extra element. 如果我使用“copy.deepcopy”,我没有额外的元素。 The output is: 输出是:

<data factor="1" name="ini" value="342" />

If I use "copy.copy", just change the name of the element. 如果我使用“copy.copy”,只需更改元素的名称即可。 The output is: 输出是:

<data factor="1" name="raw_ini" value="342" />

Any Idea of what am I doing wrong? 对我做错了什么的任何想法?

You have to get the parent of those data elements and use the Element.insert(index, element) method. 您必须获取这些data元素的父级并使用Element.insert(index, element)方法。

Also, you need to use deepcopy and not just copy . 此外,您需要使用deepcopy而不仅仅是copy The difference is that deepcopy creates a second object, whereas by using copy (which return a shallow copy of the object) you would just be modifying the first element (as you also figured out). 不同之处在于deepcopy创建了第二个对象,而通过使用copy (返回对象的浅表副本),您只需要修改第一个元素(正如您所知)。

Let's say that you have dataParent as the parent of the data elements. 假设您将dataParent作为data元素的父级。

listData = dataParent.findall('data')
lenData = len(listData)
i = 0
while i < lenData:
    if listData[i].attrib['name'] == 'ini':
        copyElem = copy.deepcopy(dataElem)
        copyElem['name'] = 'raw_ini'
        dataParent.insert([index you wish], copyElem)
    i += 1

Where did the "copy" and "dataElem" come from in the above example? 在上面的例子中,“copy”和“dataElem”来自哪里? ie copyElem = copy .deepcopy( dataElem ) 即copyElem = copy .deepcopy( dataElem

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: 复制节点(或树),并保持它的孩子,而不必导入另一个库为最简单的方法:

import xml.etree.ElementTree; import xml.etree.ElementTree;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM