XML CDATA Encoding

Nick picture Nick · Jun 9, 2009 · Viewed 12.3k times · Source

I am trying to build an XML document in C# with CDATA to hold the text inside an element. For example..

<email>
<![CDATA[[email protected]]]>
</email>

However, when I get the InnerXml property of the document, the CDATA has been reformatted so the InnerXml string looks like the below which fails.

<email>
&lt;![CDATA[[email protected]]]&gt;
</email>

How can I keep the original format when accessing the string of the XML?

Cheers

Answer

Jon Skeet picture Jon Skeet · Jun 9, 2009

Don't use InnerText: use XmlDocument.CreateCDataSection:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("root");
        XmlElement email = doc.CreateElement("email");
        XmlNode cdata = doc.CreateCDataSection("[email protected]");

        doc.AppendChild(root);
        root.AppendChild(email);
        email.AppendChild(cdata);

        Console.WriteLine(doc.InnerXml);
    }
}