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个坑,对相关同学有所帮助。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容