Search XML Attributes PowerShell XPath

In this Powershell tutorial on XML, we will discuss how to search XML and extract specific nodes, by searching XML attributes. We will use the select-Xml cmdlet for doing this, however the XPath query would be at an attribute level. Using the examples provided in this tutorial, you should be able to easily query XML data in Powershell and use the output values.

1.Input XML with Attributes


Use the following input XML for this tutorial
<Details>
        <department count="10">
                <ID>10</ID>
                <dname>Administration</dname>
                <manager>200</manager>
                <location>1700</location>
                <revenue>77</revenue>
        </department>
        <department count="20">
                <ID>20</ID>
                <dname>Marketing</dname>
                <manager>201</manager>
                <location>1800</location>
                <revenue>50</revenue>
        </department>
</Details>


2.  Load the XML in PowerShell


We will load the XML directly in PowerShell as shown in the illustration below:
PS C:\> $xml_attributes=@"
>> <Details>
>>     <department count="10">
>>         <ID>10</ID>
>>         <dname>Administration</dname>
>>         <manager>200</manager>
>>         <location>1700</location>
>>         <revenue>77</revenue>
>>     </department>
>>     <department count="20">
>>         <ID>20</ID>
>>         <dname>Marketing</dname>
>>         <manager>201</manager>
>>         <location>1800</location>
>>         <revenue>50</revenue>
>>     </department>
>> </Details>
>> "@
>>
PS C:\>

The variable xml_attributes contains the XML data that we can search upon using select-Xml cmdlet.

3. Search XML by Attributes in PowerShell - XPath


If you want to list all the "count" attribute values as an example, you can do this as per the command below.
C:\>powershell
Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. All rights reserved.

PS C:\> Select-Xml -Content $xml_attributes -XPath '//@count' | foreach {$_.node
}

#text
-----
10
20

Here, we use '//' to directly query the XML attribute and use the 'foreach' statement to print the value in Powershell.

4.List XML Nodes Matching Attribute Value - Example


In this case, the requirement is to list all the department details where the count matches 10. You can do this easily by matching the attribute value to 10 in the XPath and printing the output. The Powershell command to do this is provided below:
PS C:\> Select-Xml -Content $xml_attributes -XPath '//department[@count="10"]' |
 foreach {$_.node}


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

Once you know how to search attributes, it will be a cakewalk for you to extend this to any complex XMLs. Hope you liked this powershell tip. If you are stuck, post us your XML and question, we will solve it for you.

No comments:

Post a Comment