【问题标题】:to grep the parent pom version and replace with new valuegrep 父 pom 版本并替换为新值
【发布时间】:2023-03-16 17:16:01
【问题描述】:

我有一个 xml 文件,我需要在其中找到父版本并替换为新值。

<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>
    <parent>
        <groupId>com.test.proj</groupId>
        <artifactId>proj-core</artifactId>
        <version>1.1.0.0</version>
    </parent>
    <groupId>com.test.child</groupId>
    <artifactId>sub-module</artifactId>
    <version>2.20.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <name>test</name>
    <description>test suite</description>
</project>

在上面的 xml 中,我可以使用 mvn 命令更改模块版本,但无法使用脚本更改父版本。有没有办法grep和替换值?

我尝试使用 python 脚本进行更改

from xml.etree.ElementTree import ElementTree
print ElementTree(file="pom.xml").findtext("{http://maven.apache.org/POM/4.0.0}parent/version")

默认情况下只拍摄快照版本。

【问题讨论】:

  • 你想用什么值替换?
  • @SoumendraMishra 我想通过 jenkins 参数提供输入值例如,如果我触发 jenkins 构建,它必须首先 grep 并显示当前父版本,并且必须替换为新版本我通过 Jenkins 提供。
  • "{http://maven.apache.org/POM/4.0.0}version" 给我 SNAPSHOT 版本。 "{http://maven.apache.org/POM/4.0.0}parent/version" 什么也得不到。您是否要打印出这两个,然后都替换它们?具有相同的价值?

标签: python xml linux shell maven


【解决方案1】:

您的问题可能不完整,但至少这是答案的开始。

如果你可以使用独立工具xmlstarlet,试试这个:

xmlstarlet sel -N m=http://maven.apache.or '//m:version' -n /tmp/pom.xml 

输出:

1.1.0.0
2.20.0.0-SNAPSHOT

然后进行修改,

xmlstarlet ed -N m=http://maven.apache.org/POM/4.0.0 -u '//m:version' -v 1.2.3.4  /tmp/pom.xml

输出:

<?xml version="1.0"?>
<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>
  <parent>
    <groupId>com.test.proj</groupId>
    <artifactId>proj-core</artifactId>
    <version>1.2.3.4</version>
  </parent>
  <groupId>com.test.child</groupId>
  <artifactId>sub-module</artifactId>
  <version>1.2.3.4</version>
  <packaging>pom</packaging>
  <name>test</name>
  <description>test suite</description>
</project>

来源/灵感:https://unix.stackexchange.com/questions/398157/search-replace-in-xml-file-with-sed-or-awkXML Starlet manual

如果您想在 Python 中执行此操作,请参阅例如Find and Replace Values in XML using Python (尽管认真考虑迁移到 Python 3!)

【讨论】:

    【解决方案2】:

    您可以使用 Maven 本身来设置父版本:

    mvn versions:update-parent -DparentVersion=1.2.3

    【讨论】:

      猜你喜欢
      • 2017-02-22
      • 2019-07-24
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 2021-11-12
      • 2020-07-12
      • 2012-10-03
      • 2020-08-28
      相关资源
      最近更新 更多