The following is the 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 the range 1-4095"/>
<!--=======================================================-->
<PTYPE name="MYFIELD"
pattern="0..99"
help="Entry number"/>
<!--=======================================================-->
</CLISH_MODULE>
Here is the python code to modify xml file
import xml.etree.ElementTree as ET
tree = ET.parse('testxml.xml')
ET.register_namespace('', "http://clish.sourceforge.net/XMLSchema")
root = tree.getroot()
for child in root:
for key, value in child.items():
if value == "MYFIELD":
print value
child.attrib['pattern'] = '1..55'
tree.write('testxml.xml', encoding="UTF-8")
Here is the 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 the 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 to modify the content but there is a problem in preserving the format. Can you please share the knowledge about how to fix this issue.
After trying lot of things, tried this way by parsing the input file and making the change where the attribute and it's value matches
if value == "MYFIELD":
fin = open("testxml.xml")
fout = open("testx.xml", "wt")
for 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 the range 1-4095"/>
<!--=======================================================-->
<PTYPE name="MYFIELD"
pattern="1..55"
help="Entry number"/>
<!--=======================================================-->
</CLISH_MODULE>
not a best solution , but gives the result as expected
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.