'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?
Solution 1:[1]
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
Solution 2:[2]
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.
Solution 3:[3]
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)"));
Solution 4:[4]
[System.Xml.Linq.XDocument]::Parse($Xml.OuterXml).ToString()
Solution 5:[5]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Justin |
| Solution 2 | Emiliano Poggi |
| Solution 3 | Alexander Tuttle |
| Solution 4 | iRon |
| Solution 5 | Jared Skarstedt |
