【问题标题】:xmlstarlet select and update xmlxmlstarlet 选择和更新 xml
【发布时间】:2018-08-10 11:55:05
【问题描述】:

我正在尝试选择与特定元素(具有特定值)匹配的 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 的新手。我尝试阅读一些文档,但我真的迷路了..

【问题讨论】:

  • 我的回答有帮助还是您还有问题?
  • @DanielHaley 这非常有效。非常感谢。 (我只需要在我的原始 xml 上添加类似的命名空间)但我工作得很好。对于更新我忘了提到我想重写原始文件,发现我需要添加--inplace,但如果没有你我仍然无法计算它。非常感谢:)
  • 不客气!很高兴我能帮上忙!

标签: xml xpath xml-parsing xmlstarlet


【解决方案1】:

artifactId 不是属性,因此@artifactId 不会选择任何内容。

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

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

如果你真的想这样做:

如果 groupid = group1 和 version = 0.0.1 那么我将更新版本 到 0.0.1-完成

您应该改用ed command...

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 2013-07-16
    • 2018-08-02
    • 2023-03-23
    相关资源
    最近更新 更多