Vimes
Vimes

Reputation: 11947

Powershell, output xml to screen

I'm learning PowerShell. I can load an xml file into a variable and manipulate it. I can then call the object's save method to save to disk. I expected there to be a way to output the resulting xml to screen, though. I can't seem to find one. Is there a way, other than outputting to file and then file-to-screen?

Upvotes: 35

Views: 59196

Answers (6)

iRon
iRon

Reputation: 23788

[System.Xml.Linq.XDocument]::Parse($Xml.OuterXml).ToString()

Upvotes: 7

Alexander Tuttle
Alexander Tuttle

Reputation: 21

The cleanest solution I've found is using System.Xml.Linq.XDocument.Parse like this:

Write-Host ([System.Xml.Linq.XDocument]::Parse("$(Get-Content -path 'c:\myxml.xml' -Raw)"));

Upvotes: 2

stej
stej

Reputation: 29469

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

Upvotes: 6

Jared Skarstedt
Jared Skarstedt

Reputation: 11

This is an old thread but I wanted to share my hackish answer. I needed to send the xml to php and I couldn't send anything else.

the answer I came up with was to save the file to disk and then run a get content on it. This echoes back the xml text and nothing else:

#hack alert.  
#we need to echo out just the text of the XML back to PHP. 

IF ("$env:TEMP\xml.xml") {Remove-Item "$env:TEMP\xml.xml"}
#$xmlDoc.Save("c:\temp\xml.xml")
$xmlDoc.Save("$env:TEMP\xml.xml")
get-content "$env:TEMP\xml.xml"

In my case I was sending it back to PHP and it worked perfectly

Upvotes: 1

samaspin
samaspin

Reputation: 2402

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

Upvotes: 59

Emiliano Poggi
Emiliano Poggi

Reputation: 24826

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.

Upvotes: 24

Related Questions