Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Querying the attribute of first child of an xml element using xPath

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading