42

I am searching for a way to convert a XML-Object to string.

Is there a way like $xml.toString() in Powershell?

uprix
  • 423
  • 1
  • 4
  • 5

5 Answers5

76

You are probably looking for OuterXml.

$xml.OuterXml should give you what you want.

Prutswonder
  • 9,894
  • 3
  • 27
  • 39
Stanley De Boer
  • 4,921
  • 1
  • 23
  • 31
8

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
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • I start the XML-Object this way: [XML]$xml = ''; 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 '' – uprix Mar 14 '13 at 13:29
  • 2
    If you need it to be a string, don't make it XML. Start with a here-string, and append to that. – mjolinor Mar 14 '13 at 13:47
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.

1

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()
skeetastax
  • 1,016
  • 8
  • 18
1

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.

zett42
  • 25,437
  • 3
  • 35
  • 72