繁体   English   中英

Python ElementTree - 插入元素的副本

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

我有以下xml代码:

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

我想复制相同的信息,但名称不同。 即,最终输出应为:

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

我试着做以下事情:

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) 

如果我使用“copy.deepcopy”,我没有额外的元素。 输出是:

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

如果我使用“copy.copy”,只需更改元素的名称即可。 输出是:

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

对我做错了什么的任何想法?

您必须获取这些data元素的父级并使用Element.insert(index, element)方法。

此外,您需要使用deepcopy而不仅仅是copy 不同之处在于deepcopy创建了第二个对象,而通过使用copy (返回对象的浅表副本),您只需要修改第一个元素(正如您所知)。

假设您将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

在上面的例子中,“copy”和“dataElem”来自哪里? 即copyElem = copy .deepcopy( dataElem

备查。

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

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