xmlpowershellcdata

How can I add CData as a XElement Value in Powershell?


I've got a PS script that creates some XML and assigns values to the XElements. I need the value of the XElement to be wrapped in CData. This is using System.Xml.Linq I tried this:

$newNode.Element("details").Value = '<![CDATA[Traceback:'+$_.Exception.toString()+']]>'

but when I output the xml, it converts the '<' and '>' to &lt and &gt.


Solution

  • Add an object of type XCData to your element

    [Reflection.Assembly]::LoadWithPartialName("System.Xml.Linq") | Out-Null
    
    [System.Xml.Linq.XCData] $cdata = New-Object -TypeName System.Xml.Linq.XCdata -ArgumentList "data"
    [System.Xml.Linq.XElement] $element = New-Object -TypeName System.Xml.Linq.XElement -ArgumentList "test", $cdata