前阵子工作中用Python对xml格式的配置文件的内容进行修改,使用的模块是Python内置的xml.etree.cElementTree。然后修改maven的pom.xml的时候遇到2个问题,在这里分享下遇到的坑。
以改下面中的pom.xml为例:
4.0.0
javaTest
javatest
1.0-SNAPSHOT
com.alibaba
fastjson
1.2.9
org.testng
testng
6.9
test
现在需要改文件中的testng的版本号,因为pom.xml中的标签均没有属性,所以只能通过标签的内容来定位标签。思想是:首先先定位内容为testng的artifactId标签,那么该标签的后继兄弟标签即为version标签,其中的内容即为我们要改掉的版本号。
python代码如下:
# coding: utf-8
import xml.etree.cElementTree as ET
import re
class ConfigXMLFile(object):
def __init__(self, file):
self.config = file # 配置文件path
self.tree = None
def readXML(self, type):
'''
读取并解析xml文件
return: ElementTree
'''
self.tree = ET.ElementTree()
self.tree.parse(self.config)
def writeXML(self, out_path):
'''
将xml文件写出
out_path: 写出路径
'''
self.tree.write(out_path, encoding="utf-8", xml_declaration=True)
def configPOMVer(self, artifactId, version, out_path):
'''
修改pom中的依赖包的version
:param artifactId: artifactId
:param version: version
:param out_path: 修改后的配置文件路径
:return:
'''
pre_sibling = None
root = self.tree.getroot() # 根node
for child in root.iter("dependency"):