[python]批量修改xml中属性及字段的实现

需求描述

        批量修改当前文件夹下所有的xml文件中的版本号字段,修改componentVersion字段对应的版本号内容

xml文件

aaa.xml

<?xml version="1.0" ?><CONTENT date="2021-12-09" version="1.0">
	  <Generate>11111</Generate>
	  <Info>
	  	<Project>aaaaa</Project>
        <componentVersion>1.0</componentVersion>
	  	<Customer>CN</Customer>
	  </Info>
</CONTENT>

bbb.xml

<?xml version="1.0" ?><CONTENT date="2021-12-09" version="1.0">
	  <Generate>333333</Generate>
	  <Type>000</Type>
	  <Info>
	  	<Project>ccccc</Project>
        <componentVersion>1.0</componentVersion>
	  	<Customer>CN</Customer>
	  </Info>
</CONTENT>

ccc.xml

<?xml version="1.0" ?><CONTENT date="2021-12-09" version="1.0">
	  <Generate>11111</Generate>
	  <Info>
	  	<Project1>bbbbb</Project1>
	  	<Project2>bbbbb</Project2>
	  	<Project3>bbbbb</Project3>
	  	<Project4>bbbbb</Project4>
        <componentVersion>1.0</componentVersion>
	  	<Customer>CN</Customer>
	  </Info>
</CONTENT>

python实现代码

test.py

#coding=utf-8
import sys
import xml.dom.minidom
import os

#获取传入的版本号,sys.argv[0]是python的文件名称
version=sys.argv[1]
print 'New version' +'='+version

for root,dirs, files in os.walk("./"):
    print files #get current files
    for sfile in files:
        if os.path.splitext(sfile)[1] == '.xml':     #只修改xml文件
            #print sfile
            #打开xml文档
            dom = xml.dom.minidom.parse(sfile)
            #得到文档元素对象
            #root = dom.documentElement
            componementVersion=dom.getElementsByTagName('componentVersion')
            c1=componementVersion[0]
            print ">---------------------<"
            print sfile
            print "Old Version:"+c1.firstChild.data
            c1.firstChild.data=version
            print "New Version:"+c1.firstChild.data
            with open(os.path.join("./",sfile),'w') as fh:   #write to xml file
                dom.writexml(fh)
print ">----------end-----------<"

执行修改

root@virtual-machine:/home/test_old# python test.py 1.2
1.2
New version=1.2
['bbb.xml', 'aaa.xml', 'test.py', 'ccc.xml']
>---------------------<
bbb.xml
Old Version:1.0
New Version:1.2
>---------------------<
aaa.xml
Old Version:1.0
New Version:1.2
>---------------------<
ccc.xml
Old Version:1.0
New Version:1.2
>----------end-----------<

查看xml文件中所有componentVersion对应的版本号,实测已经修改

Guess you like

Origin blog.csdn.net/wgl307293845/article/details/121819043