[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对应的版本号,实测已经修改

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wellnw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值