Home > database >  Python - replace root element of one xml file with another root element without its children
Python - replace root element of one xml file with another root element without its children

Time:10-07

I have one xml file that looks like this, XML1:

<?xml version='1.0' encoding='utf-8'?>
<report>
</report>

And the other one that is like this, XML2:

<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla" >
    <child1>  
        <child2> 
            ....
        </child2>
    </child1>
</report>

I need to replace and put root element of XML2 without its children, so XML1 looks like this:

<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla">
</report>

Currently my code looks like this but it won't remove children but put whole tree inside:

source_tree = ET.parse('XML2.xml')
source_root = source_tree.getroot()

report = source_root.findall('report') 

for child in list(report):
     report.remove(child)
     source_tree.write('XML1.xml', encoding='utf-8', xml_declaration=True)

Anyone has ide how can I achieve this?

Thanks!

CodePudding user response:

Try the below (just copy attrib)

import xml.etree.ElementTree as ET


xml1 = '''<?xml version='1.0' encoding='utf-8'?>
<report>
</report>'''

xml2 = '''<?xml version='1.0' encoding='utf-8'?>
<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla" >
    <child1>  
        <child2> 
        </child2>
    </child1>
</report>'''

root1 = ET.fromstring(xml1)
root2 = ET.fromstring(xml2)

root1.attrib = root2.attrib

ET.dump(root1)

output

<report attrib1="blabla" attrib2="blabla" attrib3="blabla" attrib4="blabla" attrib5="blabla">
</report>

CodePudding user response:

So here is working code:

source_tree = ET.parse('XML2.xml')
source_root = source_tree.getroot()

dest_tree = ET.parse('XML1.xml')
dest_root = dest_tree.getroot()

dest_root.attrib = source_root.attrib
dest_tree.write('XML1.xml', encoding='utf-8', xml_declaration=True)
  • Related