2013-03-20 38 views
3

的副本,我有以下XML代碼:Python的ElementTree的 - 插入元素

<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" /> 

任何想法我做錯了什麼?

回答

1

你必須讓那些data元素的父元素,並使用Element.insert(index, element)方法。

此外,您還需要使用deepcopy而不僅僅是copy。不同的是,deepcopy創建第二對象,而通過使用copy(其返回對象的複製)你只是被修改的第一個元素(如你也想出)。

比方說,你有dataParentdata元素的父。

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 
+0

很抱歉,但我怎樣才能得到父? (我是新的工作與XML) – 2013-03-20 16:09:23

1

「copy」和「dataElem」從哪裏來的? 即copyElem = 拷貝 .deepcopy(dataElem

0

以供將來參考。

複製節點(或樹),並保持它的孩子,而無需導入 ANOTHERONLY

最簡單的方法:

進口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