I am searching for a way to convert a XML-Object to string.
Is there a way like $xml.toString() in Powershell?
I am searching for a way to convert a XML-Object to string.
Is there a way like $xml.toString() in Powershell?
You are probably looking for OuterXml
.
$xml.OuterXml
should give you what you want.
How are you creating the XML object?
Typically, if you want an XML string from an object, you'd use:
$object | ConvertTo-Xml -As String
Try this:
[string[]]$text = $doc.OuterXml #or use Get-Content to read an XML File
$data = New-Object System.Collections.ArrayList
[void] $data.Add($text -join "`n")
$tmpDoc = New-Object System.Xml.XmlDataDocument
$tmpDoc.LoadXml($data -join "`n")
$sw = New-Object System.IO.StringWriter
$writer = New-Object System.Xml.XmlTextWriter($sw)
$writer.Formatting = [System.Xml.Formatting]::Indented
$tmpDoc.WriteContentTo($writer)
$sw.ToString()
I used this script to write my generated XML into a TextBox in Windows Forms.
A simpler version:
[string]$outputString = $XmlObject.childNode.childNode.theElementValueIWant.ToString()
Xml path is whatever your source XML tree structure is from the $XmlObject
.
So if your $XmlObject
is:
<xmlRoot>
<firstLevel>
<secondLevel>
<iWantThisValue>THE STRING I SEEK</iWantThisValue>
</secondLevel>
</firstLevel>
</xmlRoot>
you would use:
[string]$outputString = $XmlObject.firstLevel.secondLevel.iWantThisValue.ToString()
Since PowerShell 7+, there is a very simple way to pretty-print XML using XElement
:
$xmlNode = [xml] '<foo x="42" y="21"><bar>baz</bar></foo>'
[System.Xml.Linq.XElement]::Parse( $xmlNode.OuterXml ).ToString()
Output:
<foo x="42" y="21">
<bar>baz</bar>
</foo>
As the original poster of the C# answer wrote, it's not the most efficient way in terms of memory usage and execution time. Also you don't get much control over the formatting, e. g. I didn't find a way to print attributes on new lines. If these things are important to you, the StringWriter
solution would be more appropriate.