Formatting XML Files

by May 11, 2012

Here's a cool little XML formatting tool. It takes the path to any XML file and allows you to specify an indent. Then, it saves the file as new XML file with the indentation you specified.

Here's the code for the function:

function Format-Xml  {
    param($PathXML, $Indent=2, $Destination="$env:temp\out.xml", [switch]$Open) 
    $xml = New-Object XML
    $xml.Load($PathXML)
    $StringWriter = New-Object System.IO.StringWriter 
    $XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter 
    $xmlWriter.Formatting = "indented" 
    $xmlWriter.Indentation = $Indent 
    $xml.WriteContentTo($XmlWriter) 
    $XmlWriter.Flush() 
    $StringWriter.Flush() 
    Set-Content -Value ($StringWriter.ToString()) -Path $Destination
    if ($Open) { notepad $Destination }
} 

And this is how you'd use it:

PS> Format-Xml -PathXML C:\Windows\Ultimate.xml -Open -Indent 1 
PS> Format-Xml -PathXML C:\Windows\Ultimate.xml -Open -Indent 5 

Because of -Open, the result is opened automatically in Notepad, and you can see the results of the different indentation settings. To save the formatted XML to another place, use the -Destination parameter and specify a path and name for the XML file to be created.

Twitter This Tip! ReTweet this Tip!