开发者

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?


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


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.


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


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


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)"));


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜