grep父pom版本并替换为新值

2024-04-28 02:30:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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")

默认情况下,仅获取快照版本


Tags: orgtest版本projecthttpversionapachexml
2条回答

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

mvn versions:update-parent -DparentVersion=1.2.3

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

如果可以使用独立工具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!)

相关问题 更多 >