PowerShell Script to Parse XML File Easily
[xml]$xml = Get-Content 'file.xml' to load the XML file, then access nodes like $xml.Root.Element to parse and read data.Examples
How to Think About It
[xml]. Then, navigate the XML structure by accessing elements and attributes as properties to extract the needed data.Algorithm
Code
[xml]$xml = Get-Content 'sample.xml'
foreach ($book in $xml.books.book) {
Write-Output $book.title
}Dry Run
Let's trace parsing a sample XML with two book titles through the code
Load XML content
[xml]$xml = Get-Content 'sample.xml' loads XML with books and titles
Loop through book elements
foreach loops over $xml.books.book which contains two book nodes
Output each title
Write-Output prints each book.title: 'Book1' then 'Book2'
| Iteration | Current Book Title |
|---|---|
| 1 | Book1 |
| 2 | Book2 |
Why This Works
Step 1: Load XML as object
Using [xml] converts the file content into an XML object, enabling easy property access.
Step 2: Access elements by name
XML nodes become properties, so $xml.books.book accesses all
Step 3: Iterate and output
Looping through nodes lets you extract and print each
Alternative Approaches
$xmlContent = Get-Content 'sample.xml' $nodes = Select-Xml -Xml $xmlContent -XPath '//book/title' foreach ($node in $nodes) { Write-Output $node.Node.InnerText }
$xmlDoc = New-Object -ComObject 'Microsoft.XMLDOM' $xmlDoc.Load('sample.xml') $nodes = $xmlDoc.SelectNodes('//book/title') foreach ($node in $nodes) { Write-Output $node.text }
Complexity: O(n) time, O(n) space
Time Complexity
Parsing the XML file and iterating over its nodes takes time proportional to the number of nodes, so O(n).
Space Complexity
The XML object holds the entire file in memory, so space usage grows with file size, O(n).
Which Approach is Fastest?
Casting to [xml] is fast and simple for most cases; Select-Xml adds XPath flexibility but with slight overhead; COM object is slower and less recommended.
| Approach | Time | Space | Best For |
|---|---|---|---|
| [xml] casting | O(n) | O(n) | Simple and direct XML parsing |
| Select-Xml cmdlet | O(n) | O(n) | XPath queries on XML content |
| COM XMLDocument | O(n) | O(n) | Legacy support, complex XML |