Home > other >  Querying the attribute of first child of an xml element using xPath
Querying the attribute of first child of an xml element using xPath

Time:11-01

I'm having the following small snippet:

[xml]$doc = (New-Object System.Net.WebClient).DownloadString("https://www.jetbrains.com/updates/updates.xml")

$xPath = "//product[@name='IntelliJ IDEA']//channel[@id='IC-IU-RELEASE-licensing-RELEASE']//[1]"
$node = $doc | Select-XML -XPath $xPath 

The idea is to get the latest build version for IntelliJ using the above xPath. I am interested in the line

<build number="222.4345" version="2022.2.3" releaseDate="20220726" fullNumber="222.4345.14">

and want to extract the version attribute.

Using the above xPath //product[@name='IntelliJ IDEA']//channel[@id='IC-IU-RELEASE-licensing-RELEASE']//[1] I am getting back all builds.

Switching to //product[@name='IntelliJ IDEA']//channel[@id='IC-IU-RELEASE-licensing-RELEASE']//build[1] I indeed getting the first build, but without the actual build node, which would yield the version attribute.

If I want to simply iterate over all versions using $doc | Select-XML -XPath $xPath | ForEach-Object { $_.Node.version } I am getting an empty result back. My mistake must be something trivial, but I am at a total loss.

What is the correct syntax for getting the first build node here?

CodePudding user response:

You only need a single / to describe the immediate child nodes, not //.

Using ./build[1] to get the first <build /> node under a given parent is correct, but if you want to make sure you pick the first one that has a version attribute, do ./build[@version][1]:

$firstVersion = $doc |Select-Xml -XPath "//product[@name='IntelliJ IDEA']/channel[@id='IC-IU-RELEASE-licensing-RELEASE']/build[@version][1]" |% Node |% Version
  • Related