首页 > 解决方案 > xmlstarlet 选择和更新 xml

问题描述

我正在尝试选择与特定元素(具有特定值)匹配的 xml 文件的值。例如下面的 xml 文件:

            <dependency>
                    <groupId>group1</groupId>
                    <artifactId>art1</artifactId>
                    <version>0.0.1</version>
                    <groupId>group2</groupId>
                    <artifactId>art2</artifactId>
                    <version>0.0.2</version>
                    <groupId>group3</groupId>
                    <artifactId>art3</artifactId>
                    <version>0.0.3</version>
                    <groupId>group4</groupId>
                    <artifactId>art4</artifactId>
                    <version>0.0.4</version>                        
            </dependency>

我正在尝试使用此命令,但它给出了空白响应。

xmlstarlet sel -t -v '//groupId[@artifactId="art1"]/version' -n test.xml

如果我尝试只使用这个命令,它会给我组 id 的列表

xmlstarlet sel -t -v '//groupId' -n test.xml

group1
group2
group3
group4

我只需要获取特定组 ID 的版本号,然后我将对其进行更新,例如,如果 groupid = group1 和 version = 0.0.1,那么我将使用 xmlstarlet 将版本更新为 0.0.1-done ..

任何帮助将不胜感激,因为我是使用 xmlstarlet 的新手。我尝试阅读一些文档,但我真的迷路了..

标签: xmlxpathxml-parsingxmlstarlet

解决方案


artifactId不是属性,所以@artifactId不会选择任何东西。

如果你想要versionwhen artifactId= "art1" 的值,它看起来像这样......

xmlstarlet sel -t -v "//artifactId[.='art1']/following-sibling::version[1]" test.xml

如果你真的想这样做:

如果 groupid = group1 和 version = 0.0.1 那么我会将版本更新为 0.0.1-done

您应该改用该ed命令...

xmlstarlet ed -u "//groupId[.='group1' and following-sibling::version[1] = '0.0.1']/following-sibling::version[1]" -x "concat(.,'-done')" test.xml

输出...

<dependency>
  <groupId>group1</groupId>
  <artifactId>art1</artifactId>
  <version>0.0.1-done</version>
  <groupId>group2</groupId>
  <artifactId>art2</artifactId>
  <version>0.0.2</version>
  <groupId>group3</groupId>
  <artifactId>art3</artifactId>
  <version>0.0.3</version>
  <groupId>group4</groupId>
  <artifactId>art4</artifactId>
  <version>0.0.4</version>
</dependency>

推荐阅读