Serialize class Property as CDATA in Xml

Curiosities of the C# programming language...

The following post will explain to you how to serialize an object into XML including a CDATA Xml field.

The following is an example of a class that achieves this when serialized by using two fields for the CDATA area. The one that will be exported has to be of type XmlNode, while the other that we will use internally will be of type String (in this case).

using System.Xml;
using System.Xml.Serialization;

namespace Test
{
    public class MyConfigObject
    {
        [XmlIgnore]
        public string PrivateProperty { get; set; }

        [XmlElement]
        public string ExportableProperty { get; set; }

        private XmlNode _dataExportedAsXmlNode;

        [XmlElement("DataExportedAsXml")]
        public XmlNode DataExportedAsXmlNode
        {
            get
            {
                return _dataExportedAsXmlNode;
            }
            set
            {
                _dataExportedAsXmlNode = value;
            }
        }

        [XmlIgnore]
        public string DataExportedAsXml
        {
            get
            {
                return DataExportedAsXmlNode.Value;
            }
            set
            {
                var xmlDoc = new XmlDocument();
                _dataExportedAsXmlNode = xmlDoc.CreateCDataSection(value);
            }
        }
    }
}