XML Serialization - XmlCDataSection as Serialization.XmlText

Adam Jenkin picture Adam Jenkin · Sep 9, 2009 · Viewed 15k times · Source

I am having problems serializing a cdata section using c#

I need to serialize XmlCDataSection object property as the innertext of the element.

The result I am looking for is this:

<Test value2="Another Test">
  <![CDATA[<p>hello world</p>]]>
</Test>

To produce this, I am using this object:

public class Test
{
    [System.Xml.Serialization.XmlText()]
    public XmlCDataSection value { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string value2 { get; set; }
}

When using the xmltext annotation on the value property the following error is thrown.

System.InvalidOperationException: There was an error reflecting property 'value'. ---> System.InvalidOperationException: Cannot serialize member 'value' of type System.Xml.XmlCDataSection. XmlAttribute/XmlText cannot be used to encode complex types

If I comment out the annotation, the serialization will work but the cdata section is placed into a value element which is no good for what I am trying to do:

<Test value2="Another Test">
  <value><![CDATA[<p>hello world</p>]]></value>
</Test>

Can anybody point me in the right direction to getting this to work.

Thanks, Adam

Answer

Adam Jenkin picture Adam Jenkin · Oct 22, 2009

Thanks Richard, only now had chance to get back to this. I think I have resolved the problem by using your suggestion. I have created a CDataField object using the following:

public class CDataField : IXmlSerializable
    {
        private string elementName;
        private string elementValue;

        public CDataField(string elementName, string elementValue)
        {
            this.elementName = elementName;
            this.elementValue = elementValue;
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void WriteXml(XmlWriter w)
        {
            w.WriteStartElement(this.elementName);
            w.WriteCData(this.elementValue);
            w.WriteEndElement();
        }

        public void ReadXml(XmlReader r)
        {                      
            throw new NotImplementedException("This method has not been implemented");
        }
    }