CDATA XML Encoding

I am trying to create an XML document in C # with CDATA to store text inside an element. For example..

<email>
<![CDATA[test@test.com]]>
</email>

However, when I get the InnerXml property of the document, CDATA was reformatted, so the InnerXml line looks like below, which fails.

<email>
&lt;![CDATA[test@test.com]]&gt;
</email>

How to save the original format when accessing an XML string?

Greetings

+5
source share
3 answers

Do not 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("test@test.com");

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

        Console.WriteLine(doc.InnerXml);
    }
}
+10
source

C XmlDocument:

    XmlDocument doc = new XmlDocument();
    XmlElement email = (XmlElement)doc.AppendChild(doc.CreateElement("email"));
    email.AppendChild(doc.CreateCDataSection("test@test.com"));
    string xml = doc.OuterXml;

or using XElement:

    XElement email = new XElement("email", new XCData("test@test.com"));
    string xml = email.ToString();
+6
source

All Articles