How to write CData in xml How to write CData in xml xml xml

How to write CData in xml


As described here: msdn

// Create an XmlCDataSection from your documentvar cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));// Append the cdata section to your nodexnode.AppendChild(cdata);


Do you really need it to be in CDATA, or do you just want to get the text in there in a way which won't require extra escaping in your code?

InnerText performs whatever escaping is required, so generally I'd just use

xnode.InnerText = Convert.ToString(sqlReader["story_status"]);

... but if you really want a CDATA node, you can create one yourself as per Nekresh's answer.


If you really need a CDATA section (see Jon's answer), you can achieve that like so:

XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status"); XmlCDataSection cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));xnode.InnerXml = cdata.OuterXml;

This will replace the contents of xnode, not append to it.