tags:

views:

1141

answers:

3
+2  Q: 

XML CDATA Encoding

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

+3  A: 

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);
    }
}
Jon Skeet
+1  A: 

See XmlDocument::CreateCDataSection Method for information and examples how to create CDATA nodes in an XML Document

elmuerte
+3  A: 

With XmlDocument:

    XmlDocument doc = new XmlDocument();
    XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email"));
    email.AppendChild(doc.CreateCDataSection("[email protected]"));
    string xml = doc.OuterXml;

or with XElement:

    XElement email = new XElement("email", new XCData("[email protected]"));
    string xml = email.ToString();
Marc Gravell
The new X* classes rule! XCData is even nice enough to break up strings into multiple CDATA elements that would break it (the only reserved sequence inside one: "]]>"). For example: `new XCData("]]>blah")` outputs `<![CDATA[]]]]><![CDATA[>blah]]>`, with "]]" in one CDATA element and the ">" in another.
patridge