xmlstarlet select value based on condition

2019-05-17 04:07发布

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条回答
疯言疯语
2楼-- · 2019-05-17 04:18

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
查看更多
登录 后发表回答