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>
<![CDATA[[email protected]]]>
</email>
How can I keep the original format when accessing the string of the XML?
Cheers
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);
}
}