Powershell: Convert XML to String
47,657
Solution 1
You are probably looking for OuterXml
.
$xml.OuterXml
should give you what you want.
Solution 2
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
Solution 3
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.

Author by
uprix
Updated on July 26, 2021Comments
-
uprix over 2 years
I am searching for a way to convert a XML-Object to string.
Is there a way like $xml.toString() in Powershell?
-
uprix about 11 yearsI start the XML-Object this way: [XML]$xml = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><somestuff></somestuff>'; While the script is running i append a lot of information to this object. At the end i need this XML-File to be a string, just like '<somestuff><node></node></somestuff>'
-
mjolinor about 11 yearsIf you need it to be a string, don't make it XML. Start with a here-string, and append to that.
-
AllTradesJack over 7 yearsThis worked for me too. The only problem is I lose the whitespace formatting in the transition. Any ideas on how I can either preserve or add nice tab formatting?
-
ghigad almost 7 yearsTry
$xml.PreserveWhiteSpace = $true