Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell, output xml to screen

Tags:

powershell

xml

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?

like image 437
Vimes Avatar asked May 26 '11 16:05

Vimes


People also ask

Can PowerShell read XML?

PowerShell and Reading XML filesPowerShell provides an easy way to read XML files, manipulate them and finally to save them back to disk without writing a lot of code or knowing XPath. PowerShell does this by providing the user dot notation to signify each node in the XML document.

Which PowerShell command does support XML?

The Select-Xml cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the Content, Path, or Xml parameter to specify the XML to be searched.

How do I save an XML file in PowerShell?

Using XML files is very common in the IT World and PowerShell gives us a possibility to manipulate XML files. To export XML file in PowerShell we use Export-Clixml CmdLet likewise to import the XML file in PowerShell we use Import-Clixml CmdLet but in this article, we will focus on exporting XML files.


3 Answers

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 
like image 132
samaspin Avatar answered Sep 18 '22 18:09

samaspin


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.

like image 40
Emiliano Poggi Avatar answered Sep 21 '22 18:09

Emiliano Poggi


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

like image 37
stej Avatar answered Sep 20 '22 18:09

stej