tjernigan
tjernigan

Reputation: 191

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.

Upvotes: 0

Views: 2837

Answers (3)

meataxe
meataxe

Reputation: 981

Adding this answer because google keeps redirecting here and Shay Levy's answer did not quite work for me. Note that this won't answer the original question.

To add a new element with a CDATA section to an XmlElement object, both the new element and then its CDATA element must be added to the root xml doc, before they can be assigned to the node of interest.

$xmlRoot # your xml root doc here
$xmlNode # the node in question

$newXmlElement = xmlNode.AppendChild($xmlRoot.CreateElement("newXmlElement"))            
$newXmlElement.AppendChild($xmlRoot.CreateCDataSection("your value here"))

# The following will be appended to the content of xmlNode:
# <newXmlElement><![CDATA[your value here]]><newXmlElement>

Upvotes: 0

Alex
Alex

Reputation: 5439

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

Upvotes: 1

Shay Levy
Shay Levy

Reputation: 126842

Give this a try:

$cdata = $xml.CreateCDataSection($content)
$parent = $xml.GetElementsByTagName("TagName")[0]
$parent.AppendChild($cdata)

Upvotes: 0

Related Questions