[英]Replace a dependency version in pom.xml programmatically?
Assuming I have a pom.xml containing a parent dependency like this:假设我有一个 pom.xml 包含这样的父依赖项:
<parent>
<groupId>com.example</groupId>
<artifactId>some-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
Is there a way I can replace the 1.0.0-SNAPSHOT
version programmatically, maybe via a script?有没有办法我可以通过脚本以编程方式替换1.0.0-SNAPSHOT
版本?
My use case:我的用例:
For example, I can do the following, but this will update all occurrences of 1.0.0-SNAPSHOT
in the pom.xml, and I want to limit it to just the some-parent
artifact that has a version 1.0.0-SNAPSHOT
:例如,我可以执行以下操作,但这将更新 pom.xml 中所有出现的1.0.0-SNAPSHOT
,并且我想将其限制为仅具有1.0.0-SNAPSHOT
版本some-parent
工件:
git-xargs \
--branch-name test-branch \
--github-org <your-github-org> \
--commit-message "Update pom.xml" \
sed -i 's/1.0.0-SNAPSHOT/2.0.1/g' pom.xml
As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply-commands-or-scripts-to-run As per the git-xargs docs, I can use any type of script to process the pom.xml, bash, python, ruby etc: https://github.com/gruntwork-io/git-xargs#how-to-supply -commands-or-scripts-to-run
With xmlstarlet :使用xmlstarlet :
While you can use --if
and --else
for xmlstarlet sel
(see https://stackoverflow.com/a/35671038/2703456 for example), I don't think you can use them for xmlstarlet ed
.虽然您可以将--if
和--else
用于xmlstarlet sel
(例如,请参阅https://stackoverflow.com/a/35671038/2703456 ),但我认为您不能将它们用于xmlstarlet ed
。 I hardly ever use xmlstarlet
, so I'm not entirely sure.我几乎从不使用xmlstarlet
,所以我不完全确定。
That means you'll have to do it in Bash...这意味着您必须在 Bash 中执行此操作...
$ if [[ $(xmlstarlet sel -t -v 'parent/version' pom.xml) == "1.0.0-SNAPSHOT" ]]
then xmlstarlet ed -O -u 'parent/version' -v 2.0.1 pom.xml
fi
<parent>
<groupId>com.example</groupId>
<artifactId>some-parent</artifactId>
<version>2.0.1</version>
</parent>
$ xidel -s pom.xml -e '
if (parent/version = "1.0.0-SNAPSHOT")
then x:replace-nodes(parent/version/text(),"2.0.1")
else ()
' --output-node-format=xml
<parent>
<groupId>com.example</groupId>
<artifactId>some-parent</artifactId>
<version>2.0.1</version>
</parent>
If you want the output to include an XML declaration, for xmlstarlet
remove the -O
option and for xidel
use --output-format=xml
instead.如果您希望 output 包含 XML 声明,对于xmlstarlet
删除-O
选项,对于xidel
使用--output-format=xml
代替。
With xmlstarlet
:使用xmlstarlet
:
xmlstarlet edit --omit-decl --update '//parent[artifactId="some-parent"]/version' --value '2.0.1-SNAPSHOT' pom.xml
Output: Output:
<parent>
<groupId>com.example</groupId>
<artifactId>some-parent</artifactId>
<version>2.0.1-SNAPSHOT</version>
</parent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.