This post is just a short reminder for myself, to remember how easy it is to access the content of an xml-file from within a PowerShell script.

#
# Script.ps1
#

#The content of C:\Temp\MyXml.xml
#
#<?xml version="1.0" encoding="utf-8"?>
#<AnyRoot>
#	<Names>
#		<Name Firstname="Donald" Lastname="Duck" />
#		<Name Firstname="Tim" Lastname="Tester" />
#	</Names>
#</AnyRoot>

$filename = "C:\Temp\MyXml.xml"

[xml]$fileContent = Get-Content $filename

# access the nodes with the full path including the root

foreach ($name in $fileContent.AnyRoot.Names.Name)
{
	Write-Host $name.Firstname $name.Lastname
}

Write-Host "-------------"

#use the xpath to select the node(s) without the root

$node = $fileContent.SelectSingleNode("//Names/Name[@Lastname='Tester']")

# access the content relative to the node

if ($node -ne $null)
{
	Write-Host $node.Lastname
}

Advertisements