Powershell, output xml to screen

I couldn't get the Community Extensions to work and I don't really want to have to install something extra anyway. I have found another approach on a Microsoft blog -

function WriteXmlToScreen ([xml]$xml)
{
    $StringWriter = New-Object System.IO.StringWriter;
    $XmlWriter = New-Object System.Xml.XmlTextWriter $StringWriter;
    $XmlWriter.Formatting = "indented";
    $xml.WriteTo($XmlWriter);
    $XmlWriter.Flush();
    $StringWriter.Flush();
    Write-Output $StringWriter.ToString();
}

$xml = [xml]'<root><so><user name="john">thats me</user><user name="jane">do you like her?</user></so></root>'
WriteXmlToScreen $xml

Look at PSCX module. You will find Format-Xml cmdlet that does exactly that.

Example:

Import-Module pscx
$xml = [xml]'<root><so><user name="john">thats me</user><user name="jane">do you like her?</user></so></root>'
Format-Xml -InputObject $xml

will produce:

<root>
  <so>
    <user name="john">thats me</user>
    <user name="jane">do you like her?</user>
  </so>
</root>

For more info look at help format-xml -full


The only way I know is using System.Xml properties like outerxml or innerxml. These properties should have code already indented as long as the source was.

Tags:

Xml

Powershell