Skip to content

Instantly share code, notes, and snippets.

@brovish
Forked from tiagoduarte/Parse-XmlFile.ps1
Created June 24, 2021 08:30
Show Gist options
  • Select an option

  • Save brovish/5ae28616a5753d4b26758d44a3e2fb6b to your computer and use it in GitHub Desktop.

Select an option

Save brovish/5ae28616a5753d4b26758d44a3e2fb6b to your computer and use it in GitHub Desktop.
PowerShell snippet to parse an XML file, and retrieve elements, attributes and inner values
param(
#provide the path for the input xml document
$xmlPath = "C:\temp\tiles-list-elements.xml",
#embed xml (for demo purposes)
$xmlContent = '
<Data>
<Rows>
<Row>
<Field Name="Title">Example Title A</Field>
<Field Name="BackgroundImageLocation">/_layouts/15/images/test.jpg</Field>
<Field Name="Description"/>
<Field Name="LinkLocation">/site1</Field>
<Field Name="TileOrder">1</Field>
</Row>
<Row>
<Field Name="Title">Example Title B</Field>
<Field Name="BackgroundImageLocation">/_layouts/15/images/test2.jpg</Field>
<Field Name="Description"/>
<Field Name="LinkLocation">/site2</Field>
<Field Name="TileOrder">2</Field>
</Row>
</Rows>
</Data>'
)
function ParseXml($xmlContent)
{
#we could optimize this by accessing $xmlContent.Data.Rows.Row directly
foreach($node in $xmlContent.Data)
{
write-host ("Parsing node: " + $node.Name + $nl)
foreach($rows in $node.Rows)
{
write-host (" Parsing node: " + $rows.Name + $nl)
foreach($row in $rows.Row)
{
write-host (" Parsing node: " + $row.Name + $nl)
#retrieve individual child items inner values based on their attribute name value
$title = ($row.Field | ? {$_.Name -eq "Title"}).InnerText
write-host (" Node Title : " + $title + $nl)
#parsing child items
foreach($field in $row.Field)
{
write-host (" Parsing attr: " + $field.Name)
write-host (" Node value : " + $field.InnerText + $nl)
}
}
}
}
}
clear-host
$global:nl = [Environment]::NewLine
#using file system
#$xmlContent = (Get-Content $xmlPath)
#this is where the magic happens. powershell knows xml types, which will allows us to easily parse them
ParseXml ([xml]$xmlContent)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment