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

C#.NetXmlLinq to-Xml

C# Problem Overview


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>

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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

Solution 3 - C#

Try

xElement.Element(elementName).ReplaceNodes(new XCData(value));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan WarburtonView Question on Stackoverflow
Solution 1 - C#Damien_The_UnbelieverView Answer on Stackoverflow
Solution 2 - C#jigamillerView Answer on Stackoverflow
Solution 3 - C#Ral ZarekView Answer on Stackoverflow