Python: Write a new xml file based on a xml template -
i want generate new xml file (new.xml) based on xml template (template.xml) using xml.etree.elementtree. idea change value of <name>
tag 'all' 'new' leaving rest of new.xml file looking template.xml. can change value of the<name>
new.xml not same template.xml
here 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 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 can notice, in new.xml first line missing , value of <description>
tag not have ![cdata][] structure. script wrote , using:
import xml.etree.elementtree et def load_xml(name): ''' takes xml file input. outputs elementtree , element''' tree = et.parse(name) root = tree.getroot() return tree, root if __name__ == "__main__": # change , write 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
lxml
provides compatible api, need specify strip_cdata=false
parameter, , use exact same codes everywhere else :
form lxml import etree et def load_xml(name): ''' takes xml file input. outputs elementtree , element''' # specify parser setting parser = et.xmlparser(strip_cdata=false) # pass parser actual parsing tree = et.parse(name, parser) root = tree.getroot() return tree, root if __name__ == "__main__": # change , write new xml tree, root = load_xml('template.xml') group = root.find('group') group.find('name').text = 'new' tree.write('new.xml')
Comments
Post a Comment