使用python修改XML文件(klish types.xml)

时间:2017-08-21 11:58:58

标签: python xml

以下是原始的xml文件。

<?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>

这是修改xml文件的python代码

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")

以下是生成的xml文件。

<?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>

我可以修改内容但是在保留格式方面存在问题。你能否分享一下如何解决这个问题的知识。

1 个答案:

答案 0 :(得分:1)

在尝试了很多事情之后,通过解析输入文件并在属性及其值匹配的位置进行更改来尝试这种方式

  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"') )

输出

<?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>

不是最佳解决方案,但会按预期提供结果