3

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?

Leagis
  • 175
  • 1
  • 4
  • 14

2 Answers2

3

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")
Guillaume Lemaître
  • 1,230
  • 13
  • 18
0

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
DarkLighting
  • 309
  • 2
  • 10
  • What is odd with this is that for me with Python 3 I had to do `duplicated_tree_root_element = new_tree.getroot().getroot()` because the type of what was returned by new_tree.getroot() was still "ElementTree". Did you have this? – Jesse Jan 06 '16 at 20:26
  • No, i didn't. I developed this code using Python 2. I also found out that this method does not give you a REAL COPY of the tree, it just gives me a reference for that node. But it got the job done for what i needed... – DarkLighting Jan 07 '16 at 14:20