PowerShell Select-Xml Cmdlet XPath Example

In this example, we are going to explain how to select data from XML over an XPATH in PowerShell with some basic examples. We have discussed how to read XML data in Powershell, print data on the screen and update XML data earlier. XPATH gives an administrator more power to apply conditional logic on XML and select specific data that you are searching for. We will use Select-XML cmdlet to query XML and will provide some interesting examples as we move on this tutorial.

The test XML that we will use for the XPATH query in Powershell is provided below:

Search XML – PowerShell Xpath Example

                <dname>Human Resources</dname>

Load XML Data into a PowerShell Variable

The second step is to load the XML into a powershell variable. This is done using the command as shown below:

PS C:\> $xpath_example=[xml] (Get-Content  c:\test.xml)
PS C:\> $xpath_example


Using Select-XML cmdlet in PowerShell

We are now ready to use Select-XML cmdlet and query the XML we just loaded in Powershell. To select the first “department” node in Powershell and XPATH, you run a command like the one shown below:

PS C:\> (Select-Xml -Content $xmltest -XPath /Details/department)[0].Node

ID       : 10
dname    : Administration
manager  : 200
location : 1700
revenue  : 77

This command extracts the values of the first node, with the XPath you have provided and dumps the result back to the screen.

Using Select-XML to select all the Nodes of XML in PowerShell

If you want to select all the nodes under Details, and print them in the output, you cannot repeat the command we saw above with repeating node numbers. One way to do this would be to pipe the output of Select-XML to a “foreach” cmdlet. This is illustrated below:

PS C:\> Select-Xml -Content $xmltest -XPath /Details/department|
>> foreach {$_.node }

ID       : 10
dname    : Administration
manager  : 200
location : 1700
revenue  : 77

ID       : 20
dname    : Marketing
manager  : 201
location : 1800
revenue  : 50

ID       : 30
dname    : Purchasing
manager  : 114
location : 1700
revenue  : 68

ID       : 40
dname    : Human Resources
manager  : 203
location : 2400
revenue  : 30

ID       : 50
dname    : Shipping
manager  : 121
location : 1500
revenue  : 37

This should give you a very good introduction in using Powershell to query XML with XPATH expressions. We will see some more complex XPATH examples to select XML data in the next post.

No comments:

Post a Comment