栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

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

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

需求描述

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

xml文件 aaa.xml

	  11111
	  
	  	aaaaa
        1.0
	  	CN
	  
bbb.xml

	  333333
	  000
	  
	  	ccccc
        1.0
	  	CN
	  
ccc.xml

	  11111
	  
	  	bbbbb
	  	bbbbb
	  	bbbbb
	  	bbbbb
        1.0
	  	CN
	  

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/655756.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号