DevOps | Scripts | Automation

Powershell

How to use XML xPath in PowerShell – Part-2?

In the previous post, we have gone through several different syntaxes like the Dotnet Dot (.) method for filtering XML file nodes and their values. In addition, we have seen the xPath syntaxes like Dot (.), double dot (..), and a single slash (‘/’).

If you haven’t gone through the previous article, the link is below.

In this article, we will discuss the remaining syntaxes of xPath from the w3Schools article.

https://www.w3schools.com/xml/xpath_syntax.asp

Double Slash (‘//’) method

‘//’ syntax searches nodes from the current Node no matter where they are. This syntax is quite more beneficial than the single slash (‘/’) if we know how to use it.

The below command will get the single first book node from the XML file.

$booksXml.SelectSingleNode('//book')
Select a single node with // syntax

You can also use an array for the index.

$booksXml.SelectSingleNode('//book[2]')
with array indexing

To select the multiple nodes, use SelectNodes() method.

PS C:\> $booksXml.SelectNodes('//book')
Multiple nodes

The above output is the same for the below command because it will start searching from the catalog node and search for the book nodes.

$booksXml.SelectNodes('catalog//book')
Filtering attributes with ‘@‘ syntax

To filter out the nodes based on the attributes, ‘@‘ syntax is used. For example, we need to get all the nodes which has the id attribute then use the below command.

PS C:\> $booksXml.SelectNodes("//@id")
Attribute output

As we have both the nodes with id attributes both the nodes are displayed. Now let’s say we need to filter out the book node which has the id is bk102 then,

$booksXml.SelectNodes("//book[@id='bk102']")

The above command will search the book nodes in the XML file and display the book nodes which has the id is bk102.

filter attribute

AND (|) operator

If you need to select the multiple attributes then use the ‘|‘ (AND) operator. For example, the below command will select book nodes with bk101 and bk102 attributes.

$booksXml.SelectNodes("//book[@id='bk101'] | //book[@id='bk102']")
AND (|) operator
Greater than (>) and Less than (<) Operator

You can also apply the greater than (‘>’) or the less than (‘<‘) operator with the xPath syntax as shown below.

The below command will get all the book nodes which have the price value more than 10.

$booksXml.SelectNodes("//book[price>10.0]")
Greater than (>) operator

Similarly, the below command will get all the book nodes which have the price value less than 10.

$booksXml.SelectNodes("//book[price<10.0]")
Less than (<) Operator

These are the most basic syntaxes and commands are used with XML xPath. We will cover more on this in future but these are the necessary commands to work with XML in PowerShell.

Loading

2 thoughts on “How to use XML xPath in PowerShell – Part-2?

Comments are closed.