38

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

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

uprix
  • 383
  • 1
  • 3
  • 5

5 Answers5

67

You are probably looking for OuterXml.

$xml.OuterXml should give you what you want.

Prutswonder
  • 9,476
  • 3
  • 26
  • 38
Stanley De Boer
  • 4,611
  • 1
  • 23
  • 31
9

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
  • 62,812
  • 6
  • 108
  • 130
  • 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
2

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.

0

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
  • 712
  • 4
  • 13
0

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
  • 18,406
  • 3
  • 20
  • 66