简体   繁体   中英

Python ElementTree Copy Node with childs

I have to merge multiple XML-Files into one. Furthermore the structure of the new file is different. This is my "old" structure:

<a>
    <b>
        <c>1</c>
        <c></c>
        <c></c>
        <c></c>
    </b>    
    <b>
        <c>1</c>
        <c></c>
        <c></c>
        <c></c>
    </b>        
    <b>
        <c>2</c>
        <c></c>
        <c></c>
        <c></c>
    </b>    
</a>

This should be the new one:

<a>
<1>
    <b>
        <c>1</c>
        <c></c>
        <c></c>
        <c></c>
    </b>
    <b>
        <c>1</c>
        <c></c>
        <c></c>
        <c></c>
    </b>
</1>
<2>
    <b>
        <c>2</c>
        <c></c>
        <c></c>
        <c></c>
    </b>
</2>

So I need a function which can copy a b-Element and it's childs. I dont want to use for-Loops for this. Or is that the right way?

Are you sure you really need a copy? Would reorganizing the tree be sufficient?

import xml.etree.ElementTree as ET

list_of_files = ["tree1.xml", "tree2.xml", ...]

new_tree = ET.Element("a")
i = 1
for file in list_of_files:
  original_tree = ET.parse(file)
  sub_tree = ET.SubElement(new_tree, str(i))
  i += 1
  sub_tree.append (original_tree)
new_tree.write("merged_tree.xml")

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