Search code examples
for-xml-path

XML Path expression


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
        </dependency>
        <dependency>
          <groupId>telnet</groupId>
          <artifactId>telnet.service</artifactId>
          <version>1.10.0-SNAPSHOT</version>
        </dependency>
        <dependency>
          <groupId>xmlthing</groupId>
          <artifactId>xmlthing.service</artifactId>
          <version>1.9.0-SNAPSHOT</version>
        </dependency>
        <dependency>
          <groupId>parser</groupId>
          <artifactId>parser.service</artifactId>
          <version>1.4.0-SNAPSHOT</version>
        </dependency>
    </dependencies>
</dependencyManagement>

How to be more substantive than this? I have problem extracting value from the version attribute where groupId=telnet. How can I get xmlpath value of 1.10.0-SNAPSHOT where groupId=telnet?

Sorry not for mention it before: It should be in linux/unix format (xmllint, grep, sed ...) anything :) Thanks a lot! Brgds, S.


Solution

  • You can start with selecting all version elements nested in dependency elements:

    //pom:dependency/pom:version
    

    and then qualify the dependency appropriately:

    //pom:dependency[pom:groupId = 'telnet']/pom:version
    

    Of course, you need to specify the namespaces for XPath as well.

    Quick PowerShell test:

    PS> $x | Select-Xml '//pom:dependency[pom:groupId = ''telnet'']/pom:version' -Namespace @{pom = 'http://maven.apache.org/POM/4.0.0'} | % node
    
    
    #text
    -----
    1.10.0-SNAPSHOT