我需要从大量pom.xml文件中提取Maven GAV(groupId,artifactId,version).并非所有POM都具有父POM声明,因此需要考虑父GAV和项目GAV之间的继承.
我只想使用可以在linux shell中轻松编写脚本的工具,例如bash.
我能找到的最佳解决方案是使用XSL转换.extract-gav.xsl使用以下内容创建文件:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" omit-xml-declaration="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/pom:project">
<!-- this XML element just serves as a bracket and may be omitted -->
<xsl:element name="artifact">
<xsl:text> </xsl:text>
<!-- process coordinates declared at project and project/parent -->
<xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/>
<xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/>
<xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/>
</xsl:element>
</xsl:template>
<xsl:template match="*" mode="copy-coordinate">
<!-- omit parent coordinate if same coordinate is explicitly specified on project level -->
<xsl:if test="not(../../*[name(.)=name(current())])">
<!-- write coordinate as XML element without namespace declarations -->
<xsl:element name="{local-name()}">
<xsl:value-of select="."/>
</xsl:element>
<xsl:text> </xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
然后可以使用th命令在shell中调用此转换(假设您已安装libxslt) xsltproc extract-gav.xsl pom.xml
这将以以下格式生成输出:
<artifact>
<groupId>org.example.group</groupId>
<artifactId>example-artifact</artifactId>
<version>1.2.0</version>
</artifact>
Run Code Online (Sandbox Code Playgroud)
如果您需要不同的格式,XSL转换应该很容易适应,以便它适合您的需要.例如,以下转换将GAV写为制表符分隔的纯文本:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:pom="http://maven.apache.org/POM/4.0.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/pom:project">
<!-- process coordinates declared at project and project/parent -->
<xsl:apply-templates select="pom:groupId|pom:parent/pom:groupId" mode="copy-coordinate"/>
<xsl:apply-templates select="pom:artifactId|pom:parent/pom:artifactId" mode="copy-coordinate"/>
<xsl:apply-templates select="pom:version|pom:parent/pom:version" mode="copy-coordinate"/>
<xsl:text> </xsl:text>
</xsl:template>
<xsl:template match="*" mode="copy-coordinate">
<xsl:if test="not(../../*[name(.)=name(current())])">
<xsl:value-of select="."/>
<xsl:text>	</xsl:text>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
grep -v '\[' <( mvn help:evaluate -Dexpression="project.groupId" 2>/dev/null &&
mvn help:evaluate -Dexpression="project.artifactId" 2>/dev/null &&
mvn help:evaluate -Dexpression="project.version" 2>/dev/null )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7551 次 |
| 最近记录: |