Powershell Search XML Attributes Example - Part 3

We have been discussing about the Search-Xml cmdlet in depth so far, and in this part of the series, we will see some more advanced XPath examples in Powershell. When you run through these, you will appreciate the great flexibility that you have in this command line utility to search and process XML data. We will be using a slightly different XML for this example, one with attributes. So you need to change your input XML and load it in Powershell to use the examples below.

PowerShell - Input XML for Search

We will use the sample XML as shown below. This XML has attribute information injected. I have reduced the number of "department" nodes to keep things easy.
        <department count="10">
        <department count="20">

Advanced XML XPath Search Examples - PowerShell

I have not covered loading of this XML in powershell. If you are jumping straight from the internet, make sure you read part 1 of the tutorial here. Our requirement is to select "dname" where revenue is greater than 70. Here is how you can do this using Powershell.
PS C:\> Select-Xml -Content $xmltest -XPath '/Details/department/dname [../revenue>70]'

Node                       Path                       Pattern
----                       ----                       -------
dname                      InputStream                /Details/department/dn...

PS C:\> Select-Xml -Content $xmltest -XPath '/Details/department/dname [../reven
ue>70]'| foreach {$_.node}


In first case, marked in green, we get an object returned back. In the second case, we use "foreach" to get the actual dname value. We use ".." during our search on the XML to go one level up and search for the revenue node under "department".

Using AND logic in XPath to Query XML in PowerShell

We will now run a simple example to select the complete node where manager is greater than 200 and revenue is greater than 70. This is a composite AND logic that we need to use in the XPath in PowerShell. Here is how you can do this. The output for the same input XML user earlier is also provided below:

PS C:\> Select-Xml -Content $xmltest -XPath '/Details/department[manager >= 200
and revenue>70]'| foreach {$_.node}

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

You can also get a single tag value for this case, but following the example earlier. That completes part 3 of the XPath tutorial in PowerShell. This is getting interesting now. We will cover more XML search capabilities in Powershell in the next part of this series. Stay Connected.

No comments:

Post a Comment