简体   繁体   中英

Python ElementTree - Inserting a copy of an element

I have the following xml code:

<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. The output is:

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

If I use "copy.copy", just change the name of the element. 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.

Also, you need to use deepcopy and not just 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).

Let's say that you have dataParent as the parent of the data elements.

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? ie 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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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