[英]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.