-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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