xmlstarlet 根据条件选择值

问题描述:

基于此链接,我正在尝试解决类似的问题.

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>

如果 artifactId 等于 iwidget,我想提取 groupId.

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

上面返回了 groupId = foo.bar,但是,我希望它仅在 artifactId 等于 iwidget

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

我错过了什么?

以您的第一个命令为基础,您应该能够在 project 上应用一个简单的 XPath 谓词以通过 artifactId 对其进行过滤 元素值:

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

关于变量的使用,您需要用引号将其包裹起来,以便XPath处理器将其识别为字符串文字:

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