Kategorier

# Pretty print XML using Powershell

I recently came across an old application that uses a XML file for logging, but it did n ot add line breaks to the XML. This makes it impossible to search the log files using normal text file utilities, since all the log content is on the same line.

To make the log files easier to read, I needed to format the XML with line breaks, also known as “pretty print” the XML.

This can easily be done with Powershell: Just load the XML with the built-in XML parser, and the write it again.

$x = [xml](Get-Content .\in.xml)$x.Save(”C:\Users\Kalle\Desktop\out.xml”)

The only thing to watch out for is that the .Save()-metod does not write in the current directory. You have to use an absolute path to write the file.

To pretty-print all the XML files in the current directory, use the following PowerShell snippet:

Get-ChildItem -Path . -Filter *.xml |
ForEach-Object {
$x = [xml](Get-Content$_.FullName)
$x.Save($_.FullName)
}

And of course, it can be a one-liner:

dir *.xml | % { ([xml](gc $_)).Save($_) }