PowerShell – XML

This is how easy it is to parse an XML file with PowerShell!

[xml]$xml = Get-Content .\data.xml

Example XML:

<?xml version="1.0" encoding="UTF-8"?>
    <Entry Category="Animal">Dog</Entry>
    <Entry Category="Animal">Cat</Entry>
    <Entry Category="Animal">Cow</Entry>
    <Entry Category="City">New York</Entry>
    <Entry Category="City">Paris</Entry>
    <Entry Category="City">London</Entry>

Example using the XML data:

foreach($em in $xml.Entries.Entry) { Write-Host "$($em.InnerText) is a type of $($em.Attributes['Category'].Value)" }
Dog is a type of Animal
Cat is a type of Animal
Cow is a type of Animal
New York is a type of City
Paris is a type of City
London is a type of City

XPath support is also built-in:

$xml.Entries.SelectNodes("//Entry[contains(@Category, 'City')]")
Category #text
-------- -----
City New York
City Paris
City London

To get more information on the return type of a statement use the GetType() method.

Leave a Reply

Your email address will not be published. Required fields are marked *