前陣子工作中用Python對(duì)xml格式的配置文件的內(nèi)容進(jìn)行修改,使用的模塊是Python內(nèi)置的xml.etree.cElementTree攀操。然后修改maven的pom.xml的時(shí)候遇到2個(gè)問題齿兔,在這里分享下遇到的坑。
以改下面中的pom.xml為例:
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>javaTest</groupId>
<artifactId>javatest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.9</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
現(xiàn)在需要改文件中的testng的版本號(hào),因?yàn)閜om.xml中的標(biāo)簽均沒有屬性善涨,所以只能通過標(biāo)簽的內(nèi)容來定位標(biāo)簽。思想是:首先先定位內(nèi)容為testng的artifactId標(biāo)簽草则,那么該標(biāo)簽的后繼兄弟標(biāo)簽即為version標(biāo)簽钢拧,其中的內(nèi)容即為我們要改掉的版本號(hào)。
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"):
for sub_child in child:
if sub_child.text == artifactId:
pre_sibling = sub_child
if sub_child.tag == "version" and pre_sibling is not None:
sub_child.text = version
self.writeXML(out_path) # 修改version
print("修改" + str(artifactId) + "的version為:" + str(version))
return
if pre_sibling is None:
print("Error: 沒找到對(duì)應(yīng)結(jié)點(diǎn)!\n")
print(" ")
if __name__ == "__main__":
pom_config = r"E:\llf_test\llf_java\pom.xml"
artifactId = "testng"
version = "6.10"
# 修改pom.xml
pom_xml = ConfigXMLFile(pom_config)
pom_xml.readXML("pom")
pom_xml.configPOMVer(artifactId, version, pom_config)
print("修改pom.xml完成炕横!")
運(yùn)行代碼后報(bào)錯(cuò)源内,提示找不到標(biāo)簽。找原因找了好久份殿,后來網(wǎng)上搜答案膜钓,看到一個(gè)老外在stack overflow上同樣提出了這個(gè)問題塔鳍,后來他自己找到了答案。我們回頭再看pom.xml呻此,根標(biāo)簽為project轮纫。我們?cè)诖a里看下根標(biāo)簽是不是project。
def getRootTag(self):
root = self.tree.getroot() # 根node
print(root.tag)
運(yùn)行結(jié)果為:
{http://maven.apache.org/POM/4.0.0}project
好奇怪焚鲜,根元素是“{http://maven.apache.org/POM/4.0.0}project”掌唾。
我們?cè)賮砜聪挛募懈氐暮⒆釉氐臉?biāo)簽是什么?
def getChildrenOfRoot(self):
root = self.tree.getroot()
for child in root:
print(child.tag)
運(yùn)行結(jié)果為:
{http://maven.apache.org/POM/4.0.0}modelVersion
{http://maven.apache.org/POM/4.0.0}groupId
{http://maven.apache.org/POM/4.0.0}artifactId
{http://maven.apache.org/POM/4.0.0}version
{http://maven.apache.org/POM/4.0.0}dependencies
同樣忿磅,所有標(biāo)簽都有前綴“{http://maven.apache.org/POM/4.0.0}”糯彬。回過頭再看pom.xml葱她,發(fā)現(xiàn)根元素project標(biāo)簽有一些屬性:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
這個(gè)xmlns是xml文件的命名空間的概念撩扒,搜了下概念引用如下:
XML Namespace (xmlns) 屬性
XML 命名空間屬性被放置于元素的開始標(biāo)簽之中,并使用以下的語法:
xmlns:namespace-prefix="namespaceURI"
當(dāng)命名空間被定義在元素的開始標(biāo)簽中時(shí)吨些,所有帶有相同前綴的子元素都會(huì)與同一個(gè)命名空間相關(guān)聯(lián)搓谆。
默認(rèn)的命名空間(Default Namespaces)
為元素定義默認(rèn)的命名空間可以讓我們省去在所有的子元素中使用前綴的工作。使用語法如下:
xmlns="namespaceURI"
所以豪墅,pom.xml里每個(gè)元素的前綴{http://maven.apache.org/POM/4.0.0}即為namespaceURI泉手,我們看pom中project的屬性xmlns="http://maven.apache.org/POM/4.0.0",從這里可以知道偶器,namespace-prefix是沒有的斩萌。
因?yàn)槲覀兊哪康氖歉牡粑募膬?nèi)容,現(xiàn)在找不到標(biāo)簽屏轰,發(fā)現(xiàn)所有標(biāo)簽都有namespaceURI颊郎,那我們就把代碼中我們要定位的標(biāo)簽名前加上namespaceURI就好了。代碼如下:
def configPOMVer(self, artifactId, version, out_path):
'''
修改pom中的依賴包的version
:param name: 服務(wù)名
:param host: 服務(wù)host
:param out_path: 修改后的配置文件路徑
:return:
'''
pre_sibling = None
root = self.tree.getroot() # 根node
pre = (re.split('project', root.tag))[0] # 獲取pom元素tag的pre
for child in root.iter(pre + "dependency"):
for sub_child in child:
if sub_child.text == artifactId:
pre_sibling = sub_child
if sub_child.tag == (pre + "version") and pre_sibling is not None:
sub_child.text = version
self.writeXML(out_path) # 修改version
print("修改" + str(artifactId) + "的version為:" + str(version))
return
if pre_sibling is None:
print("Error: 沒找到對(duì)應(yīng)結(jié)點(diǎn)!\n")
print(" ")
運(yùn)行程序霎苗,輸出結(jié)果:
修改testng的version為:6.10
修改pom.xml完成姆吭!
看來是ok了,我們?nèi)ッ橐谎鄹倪^的pom.xml文件叨粘。
<?xml version='1.0' encoding='utf-8'?>
<ns0:project xmlns:ns0="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<ns0:modelVersion>4.0.0</ns0:modelVersion>
<ns0:groupId>javaTest</ns0:groupId>
<ns0:artifactId>javatest</ns0:artifactId>
<ns0:version>1.0-SNAPSHOT</ns0:version>
<ns0:dependencies>
<ns0:dependency>
<ns0:groupId>com.alibaba</ns0:groupId>
<ns0:artifactId>fastjson</ns0:artifactId>
<ns0:version>1.2.9</ns0:version>
</ns0:dependency>
<ns0:dependency>
<ns0:groupId>org.testng</ns0:groupId>
<ns0:artifactId>testng</ns0:artifactId>
<ns0:version>6.10</ns0:version>
<ns0:scope>test</ns0:scope>
</ns0:dependency>
</ns0:dependencies>
</ns0:project>
尼瑪猾编!文件中所有標(biāo)簽都加了個(gè)前綴ns0瘤睹,這個(gè)ns0就是namespace-prefix升敲。為什么會(huì)這里會(huì)出現(xiàn)ns0,這跟xml.etree.cElementTree模塊本身有關(guān)轰传。解決方法是使用xml.etree.ElementTree.register_namespace(prefix,uri)方法驴党,去重新定義我們的namespace-prefix,否則的話會(huì)默認(rèn)將namespace-prefix設(shè)置為ns0获茬。我們看下該方法的官方說明:
"""Register a namespace prefix.
The registry is global, and any existing mapping for either the
given prefix or the namespace URI will be removed.
*prefix* is the namespace prefix, *uri* is a namespace uri. Tags and
attributes in this namespace will be serialized with prefix if possible.
ValueError is raised if prefix is reserved or is invalid.
"""
這里的prefix即為namespace-prefix港庄,url即為namespaceURI倔既。
這里我們?cè)囼?yàn)一下,設(shè)置這2個(gè)變量的值如下:
def readXML(self, type):
'''
讀取并解析xml文件
return: ElementTree
'''
self.tree = ET.ElementTree()
if type == "pom":
XML_NS_NAME = "hello"
XML_NS_VALUE = "http://maven.apache.org/POM/4.0.0"
ET.register_namespace(XML_NS_NAME, XML_NS_VALUE)
self.tree.parse(self.config)
運(yùn)行后鹏氧,查看pom.xml文件內(nèi)容:
<?xml version='1.0' encoding='utf-8'?>
<hello:project xmlns:hello="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<hello:modelVersion>4.0.0</hello:modelVersion>
<hello:groupId>javaTest</hello:groupId>
<hello:artifactId>javatest</hello:artifactId>
<hello:version>1.0-SNAPSHOT</hello:version>
<hello:dependencies>
<hello:dependency>
<hello:groupId>com.alibaba</hello:groupId>
<hello:artifactId>fastjson</hello:artifactId>
<hello:version>1.2.9</hello:version>
</hello:dependency>
<hello:dependency>
<hello:groupId>org.testng</hello:groupId>
<hello:artifactId>testng</hello:artifactId>
<hello:version>6.10</hello:version>
<hello:scope>test</hello:scope>
</hello:dependency>
</hello:dependencies>
</hello:project>
哈哈渤涌,看到?jīng)],標(biāo)簽前的ns0換為hello了把还。前面提到实蓬,pom.xml中project的屬性xmlns="http://maven.apache.org/POM/4.0.0"是沒有設(shè)置namespace-prefix的
,所以這里就將XML_NS_NAME賦值為空字符串就好吊履,如下:
def readXML(self, type):
'''
讀取并解析xml文件
return: ElementTree
'''
self.tree = ET.ElementTree()
if type == "pom":
XML_NS_NAME = ""
XML_NS_VALUE = "http://maven.apache.org/POM/4.0.0"
ET.register_namespace(XML_NS_NAME, XML_NS_VALUE)
self.tree.parse(self.config)
運(yùn)行后安皱,查看pom.xml:
<?xml version='1.0' encoding='utf-8'?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>javaTest</groupId>
<artifactId>javatest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
ok,這下標(biāo)簽沒有前綴了艇炎。
最后總結(jié)下酌伊,因?yàn)閜om.xml有命名空間,所以改該類文件需要注意兩點(diǎn)缀踪,
1居砖、遍歷標(biāo)簽時(shí),標(biāo)簽名前要加前綴驴娃。
2悯蝉、解析文件時(shí),記得設(shè)置環(huán)境變量XML_NS_NAME和XML_NS_VALUE托慨,這里pom.xml的namespace-prefix沒有鼻由,所以XML_NS_NAME設(shè)置為“”。
希望我遇到的這2個(gè)坑厚棵,對(duì)相關(guān)同學(xué)有所幫助蕉世。