PowerShell Parse XML Simple Examples

In the previous example, we examined how to load XML data from a file into Powershell and do a simple print of the XML nodes. In this short article, we will extend the example and see how to parse the XML file we loaded. We will use the same XML file that we used in the previous article. If we want to try some complex examples, we will modify the document as required and provide you an updated version. I'm writing this tutorial in a FAQ format. At the end of this tutorial, we will also see the shortcomings in this approach, and how to mitigate them.

How to print all nodes using Powershell?


To print all the nodes for the example we examined earlier, we use the command as shown below:

PS C:\> [xml] $my_xml_data=Get-Content c:\read_xml_example.xml
PS C:\> $my_xml_data.departments.item

deptid                     deptname                   employeecount
------                     --------                   -------------
100                        marketing                  100
101                        finance                    75
102                        HR                         15
103                        IT                         250
104                        Operations                 50

This command takes every "item" node from the XML and dumps it in the output. [ Please take the XML from the example provided earlier ]

How to print a specific node, all the child elements in Powershell?


To print a specific node, say first item node, we use the command as shown below: (we use the number against the node)

PS C:\> $my_xml_data.departments.item[0]

deptid                     deptname                   employeecount
------                     --------                   -------------
100                        marketing                  100


PS C:\> $my_xml_data.departments.item[1]

deptid                     deptname                   employeecount
------                     --------                   -------------
101                        finance                    75

How to print a specific tag inside an item node in Powershell?


If you need only the employee count for item node 1, you can do this by following the example shown below:

PS C:\> $my_xml_data.departments.item[1].employeecount
75

These simple approaches to parse the XML helps if your requirement is to read a value straight without much logic involved. If you are really looking for XPath or XQuery kind of parsing to be done on a XML you cannot use this approach.

In the next tutorial, we will look into parsing some complex XMLs. We will see how we can apply conditional logic on an XML in Powershell, to get the output we want. 

No comments:

Post a Comment