Home/PowerShell/Reading XML Files With PowerShell

Reading XML Files With PowerShell

Handling XML with PowerShell is very simple. Its converts XML elements to properties on .NET objects without the need to write any parsing code. So it is very easy to use XML with PowerShell. Here we are going to discuss about how to read the XML file values in different ways.

A Quick Example

XML File : MyXM.xml’

Method 1:

Once you’ve run Get-Content to read the raw text from the XML document and cast the output to type [XML], you now have a variable called $XmlDocument that contains the entire XML node tree which we can process.

STEP 1: Assign the XML file location in to the variable.

$XMLfile = ‘C:\donet-helpers\Demo\MyXM.xml’

STEP 2: Read the xml file using get-content cmdlet and assign to variable. The [xml] casts the variable as an XML object.

[XML]$empDetails = Get-Content $XMLfile

STEP 3: Looping the child node to get the value.

foreach($empDetail in $empDetails.EmpDetails.Person){ }

Full Sample:

OUTPUT:

Method 2:

STEP 1: Assign the XML file location in to the variable.

$Path = “C:\donet-helpers\Demo\MyXM.xml”

STEP 2: The below command saves the XML path to the AliasProperty node in the $XPath variable.

$XPath = “/EmpDetails/Person”

STEP 3: The Select-Xml cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.

Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExpandProperty Node

Full Sample:

 

What do you think?

I hope you have an idea of  how to Reading XML Files With PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply