52

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>
Ian Warburton
  • 15,170
  • 23
  • 107
  • 189

3 Answers3

49

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));
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
45

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));
jigamiller
  • 513
  • 6
  • 7
43

Try

xElement.Element(elementName).ReplaceNodes(new XCData(value));
Ral Zarek
  • 1,058
  • 4
  • 18
  • 25
  • Thanks :) and just to add for me I needed the CDATA to replace another element which had more sibling nodes so used ReplaceWith but the idea came from your answer. – Rameez Ahmed Sayad Jul 24 '13 at 07:16