XML Pretty Print in PowerShell

This has probably already been done several times but here’s my take on an XML pretty print function written in PowerShell:
 
function XmlPrettyPrint([string]$xml) {
    $tr = new-object System.IO.StringReader($xml)
    $settings = new-object System.Xml.XmlReaderSettings
    $settings.CloseInput = $true
    $settings.IgnoreWhitespace = $true
    $reader = [System.Xml.XmlReader]::Create($tr, $settings)
   
    $sw = new-object System.IO.StringWriter
    $settings = new-object System.Xml.XmlWriterSettings
    $settings.CloseOutput = $true
    $settings.Indent = $true
    $writer = [System.Xml.XmlWriter]::Create($sw, $settings)
   
    while (!$reader.EOF) {
        $writer.WriteNode($reader, $false)
    }
    $writer.Flush()
   
    $result = $sw.ToString()
    $reader.Close()
    $writer.Close()
    $result
}
Advertisements
This entry was posted in PowerShell. Bookmark the permalink.

2 Responses to XML Pretty Print in PowerShell

  1. Sung says:

    Scott Hanselman did do a post about it and I have tried to modify his function to accept a pipeline input but it just doesn\’t look pretty although the output might look pretty 😉
    http://www.hanselman.com/blog/AnXmlTidyInPowerShellOrFormattingXmlWithIndentingWithPowerShell.aspx

  2. Keith says:

    OK, you shamed me into writing a better one.  See the next blog post.  🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s