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

Ian Warburton picture Ian Warburton · Mar 2, 2012 · Viewed 22.8k times · Source

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>

Answer

Damien_The_Unbeliever picture Damien_The_Unbeliever · Mar 2, 2012

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));