xmlstarlet select value based on condition

不羁的心 提交于 2019-12-10 10:17:33

问题


Based on this link, I am trying to solve a similar problem.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.foo</groupId>
  <artifactId>iwidget</artifactId>
  <packaging>jar</packaging>
  <version>0.9.1b</version>
  <name>iwidget</name>
  <url>http://maven.apache.org</url>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

I want to extract the groupId if artifactId is equal to iwidget.

What I have tried so far:

xmlstarlet sel -N x=http://maven.apache.org/POM/4.0.0 -t -v "/x:project/x:groupId" < pom.xml

Above returned the groupId = foo.bar, however, I want it to return only if artifactId is equal to iwidget

$VAR='foo.bar'
xmlstarlet sel -N x=http://maven.apache.org/POM/4.0.0 -t -m "//x:project[artifactId="$VAR"]" -v "//x:project/groupId" < pom.xml

What am I missing ?


回答1:


Building on your first command, you should be able to apply a simple XPath predicate on project to filter it by artifactId element value :

xmlstarlet sel -N x=http://maven.apache.org/POM/4.0.0 -t \
    -v "/x:project[x:artifactId='iwidget']/x:groupId" < pom.xml

Regarding the use of variable, you need to wrap it with quotes so that the value will be recognized as string literal by the XPath processor :

xmlstarlet sel -N x=http://maven.apache.org/POM/4.0.0 -t \
    -v "/x:project[x:artifactId='$VAR']/x:groupId" < pom.xml


来源:https://stackoverflow.com/questions/42826752/xmlstarlet-select-value-based-on-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!