Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the value of an XElement be wrapped in ![CDATA[***]]?

This is when using XDocument from .net.

I thought this might work...

xElement.Element(elementName).Value = new XCData(value).ToString(); 

... but it comes out like this...

<name>&lt;![CDATA[hello world]]&gt;</name> 
like image 599
Ian Warburton Avatar asked Mar 02 '12 10:03

Ian Warburton


2 Answers

XCData is a type of XNode. As such, you should try to Add it to the element, rather than set the value (which is documented to be the flattened text content of the element):

xElement.Element(elementName).Add(new XCData(value)); 
like image 134
Damien_The_Unbeliever Avatar answered Sep 23 '22 18:09

Damien_The_Unbeliever


If you are creating the XElement (vs. modifying it), you can also just add add it directly in the constructor as the content like so:

new XElement(elementName, new XCData(value)); 
like image 44
jigamiller Avatar answered Sep 20 '22 18:09

jigamiller