I want to generate a new xml file (new.xml) based on a xml template (template.xml) using xml.etree.ElementTree. The idea is to change only the value of the <name>
tag from 'all' to 'New' leaving the rest of the new.xml file looking exactly as the template.xml. I can change the value of the<name>
but the new.xml does not look exactly the same as template.xml
Here is the template.xml:
<?xml version="1.0"?>
<example>
<version>15.0</version>
<lastchange/>
<theme>black</theme>
<group>
<name>all</name>
<description><![CDATA[All Users]]></description>
<scope>system</scope>
<gid>1998</gid>
</group>
</example>
and here is the new.xml:
<example>
<version>15.0</version>
<lastchange />
<theme>black</theme>
<group>
<name>New</name>
<description>All Users</description>
<scope>system</scope>
<gid>1998</gid>
</group>
</example>
As you can notice, in the new.xml the first line is missing and the value of the <description>
tag does not have ![CDATA][] structure. This is the script I wrote and I am using:
import xml.etree.ElementTree as ET
def load_xml(name):
''' Takes an xml file as input. Outputs ElementTree and element'''
tree = ET.parse(name)
root = tree.getroot()
return tree, root
if __name__ == "__main__":
# Change and write the new xml
tree, root = load_xml('template.xml')
group = root.find('group')
group.find('name').text = 'New'
tree.write('new.xml')
Any help? Thank you