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.

Share:
47,657
uprix
Author by

uprix

Updated on July 26, 2021

Comments

  • uprix
    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
    uprix about 11 years
    I 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
    mjolinor about 11 years
    If you need it to be a string, don't make it XML. Start with a here-string, and append to that.
  • AllTradesJack
    AllTradesJack over 7 years
    This 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
    ghigad almost 7 years
    Try $xml.PreserveWhiteSpace = $true