Python改寫maven的pom.xml文件

前陣子工作中用Python對xml格式的配置文件的內容進行修改,使用的模塊是Python內置的xml.etree.cElementTree。然后修改maven的pom.xml的時候遇到2個問題,在這里分享下遇到的坑。
以改下面中的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>

現在需要改文件中的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"):
            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: 沒找到對應結點!\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完成!")

運行代碼后報錯,提示找不到標簽。找原因找了好久,后來網上搜答案,看到一個老外在stack overflow上同樣提出了這個問題,后來他自己找到了答案。我們回頭再看pom.xml,根標簽為project。我們在代碼里看下根標簽是不是project。

def getRootTag(self):
        root = self.tree.getroot()  # 根node
        print(root.tag)

運行結果為:

{http://maven.apache.org/POM/4.0.0}project

好奇怪,根元素是“{http://maven.apache.org/POM/4.0.0}project”。
我們再來看下文件中根元素的孩子元素的標簽是什么?

def getChildrenOfRoot(self):
        root = self.tree.getroot()
        for child in root:
            print(child.tag)

運行結果為:

{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

同樣,所有標簽都有前綴“{http://maven.apache.org/POM/4.0.0}”。回過頭再看pom.xml,發現根元素project標簽有一些屬性:

<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">

這個xmlns是xml文件的命名空間的概念,搜了下概念引用如下:

XML Namespace (xmlns) 屬性
XML 命名空間屬性被放置于元素的開始標簽之中,并使用以下的語法:
xmlns:namespace-prefix="namespaceURI"
當命名空間被定義在元素的開始標簽中時,所有帶有相同前綴的子元素都會與同一個命名空間相關聯。
默認的命名空間(Default Namespaces)
為元素定義默認的命名空間可以讓我們省去在所有的子元素中使用前綴的工作。使用語法如下:
xmlns="namespaceURI"

所以,pom.xml里每個元素的前綴{http://maven.apache.org/POM/4.0.0}即為namespaceURI,我們看pom中project的屬性xmlns="http://maven.apache.org/POM/4.0.0",從這里可以知道,namespace-prefix是沒有的。
因為我們的目的是改掉文件的內容,現在找不到標簽,發現所有標簽都有namespaceURI,那我們就把代碼中我們要定位的標簽名前加上namespaceURI就好了。代碼如下:

def configPOMVer(self, artifactId, version, out_path):
        '''
        修改pom中的依賴包的version
        :param name: 服務名
        :param host: 服務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: 沒找到對應結點!\n")
            print(" ")

運行程序,輸出結果:

修改testng的version為:6.10
修改pom.xml完成!

看來是ok了,我們去瞄一眼改過的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>

尼瑪!文件中所有標簽都加了個前綴ns0,這個ns0就是namespace-prefix。為什么會這里會出現ns0,這跟xml.etree.cElementTree模塊本身有關。解決方法是使用xml.etree.ElementTree.register_namespace(prefix,uri)方法,去重新定義我們的namespace-prefix,否則的話會默認將namespace-prefix設置為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。
這里我們試驗一下,設置這2個變量的值如下:

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)

運行后,查看pom.xml文件內容:

<?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>

哈哈,看到沒,標簽前的ns0換為hello了。前面提到,pom.xml中project的屬性xmlns="http://maven.apache.org/POM/4.0.0"是沒有設置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)

運行后,查看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,這下標簽沒有前綴了。
最后總結下,因為pom.xml有命名空間,所以改該類文件需要注意兩點,
1、遍歷標簽時,標簽名前要加前綴。
2、解析文件時,記得設置環境變量XML_NS_NAME和XML_NS_VALUE,這里pom.xml的namespace-prefix沒有,所以XML_NS_NAME設置為“”。
希望我遇到的這2個坑,對相關同學有所幫助。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容