Modifying XML file using python (klish types.xml) -
the following original xml file.
<?xml version="1.0" encoding="utf-8"?> <clish_module xmlns="http://clish.sourceforge.net/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://clish.sourceforge.net/xmlschema http://clish.sourceforge.net/xmlschema/clish.xsd"> <!--=======================================================--> <ptype name="vlan_id" pattern="(409[0-5]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[1-9])" help="number in range 1-4095"/> <!--=======================================================--> <ptype name="myfield" pattern="0..99" help="entry number"/> <!--=======================================================--> </clish_module> here python code modify xml file
import xml.etree.elementtree et tree = et.parse('testxml.xml') et.register_namespace('', "http://clish.sourceforge.net/xmlschema") root = tree.getroot() child in root: key, value in child.items(): if value == "myfield": print value child.attrib['pattern'] = '1..55' tree.write('testxml.xml', encoding="utf-8") here resulted xml file.
<?xml version='1.0' encoding='utf-8'?> <clish_module xmlns="http://clish.sourceforge.net/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://clish.sourceforge.net/xmlschema http://clish.sourceforge.net/xmlschema/clish.xsd"> <ptype help="number in range 1-4095" name="vlan_id" pattern="(409[0-5]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[1-9])" /> <ptype help="entry number" name="myfield" pattern="1..55" /> </clish_module> i'm able modify content there problem in preserving format. can please share knowledge how fix issue.
after trying lot of things, tried way parsing input file , making change attribute , it's value matches
if value == "myfield": fin = open("testxml.xml") fout = open("testx.xml", "wt") line in fin: xm= 'pattern="'+child.attrib['pattern']+'"' fout.write( line.replace(xm, 'pattern="1..55"') ) output
<?xml version="1.0" encoding="utf-8"?> <clish_module xmlns="http://clish.sourceforge.net/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://clish.sourceforge.net/xmlschema http://clish.sourceforge.net/xmlschema/clish.xsd"> <!--=======================================================--> <ptype name="vlan_id" pattern="(409[0-5]|40[0-8][0-9]|[1-3][0-9]{3}|[1-9][0-9]{2}|[1-9][0-9]|[1-9])" help="number in range 1-4095"/> <!--=======================================================--> <ptype name="myfield" pattern="1..55" help="entry number"/> <!--=======================================================--> </clish_module> not best solution , gives result expected
Comments
Post a Comment