Monday, August 9, 2010

Serializing with CDATA as the content of an element

Recently I came across the problem where I needed to serialize a property of type string whose content contained a CDATA element section - the content of the property/element was HTML markup. If you serialize the property using the XmlSerializer out of the box, you get the following example:

&lt ;![CDATA[&lt ;h3&gt ;Service Job 1561245&lt ;/h3&gt ;

The solution is to update the property type from string to XmlCDataSection. You can leave the field type to string (so that's descriptionField in the below example), but the get and set of the property needs to look something like this:


get
{
XmlDocument xmlDocument = new XmlDocument();
return xmlDocument.CreateCDataSection(descriptionField);
}
set
{
descriptionField = value.Value;
}

No comments:

Post a Comment