导读
本篇文章意在演示如何利用 python 解析 xml 文件。这篇文章的引出背景是,在程序开发过程中,一贯坚持的做法是「约定优于配置」,
但怎么取检测有没有按照约定去做的,以 maven 为例,maven 提供了maven-enforcer-plugin
插件,可以用这个插件定制一系列
规则。所以我们需要做的就是用 python 在 pom 文件中插入maven-enforcer-plugin
的配置 。python 环境: 3.8
本文首发于 https://russellgao.cn/python-maven-enforcer-plugins/ ,转载请注明原文出处。
目标
拿到一个 pom.xml 文件之后,python 实现对其插入 maven-enforcer-plugin
,然后进行 mvn validate
。
pom.xml 选取以开源项目 arthas 为例 : https://raw.githubusercontent.com/alibaba/arthas/master/pom.xml
maven-enforcer-plugin 配置如下 :
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M3</version>
<executions>
<execution>
<id>enforce-no-snapshots</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireReleaseDeps>
<message>No Snapshots Allowed!</message>
</requireReleaseDeps>
</rules>
<fail>true</fail>
</configuration>
</execution>
</executions>
</plugin>
需要实现的就是 maven-enforcer-plugin
的内容集成到 pom.xml 文件中。接下来主要介绍如何用 python 自动化的实现。
解析
解析主要用到了 xml
库进行解析,详细用法可以参考 官方文档
加载数据:
import xml.etree.ElementTree as ET
tree = ET.parse('pom.xml')
root = tree.getroot()
或者
import xml.etree.ElementTree as ET
tree = ET.fromstring(open('pom.xml').read())
root = 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}parent
{
http://maven.apache.org/POM/4.0.0}licenses
{
http://maven.apache.org/POM/4.0.0}scm
{
http://maven.apache.org/POM/4.0.0}developers
{
http://maven.apache