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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With