The (Unofficial) ITWorx Technical Architecture Blog

Serializing a string within CDATA element

Posted by archworx on January 22, 2007

What if we want to serialize a field of type string; which has some invalid characters to be used as an XML text, like the “<” sign?! Using these characters as is, will generate an error by the XML parser. In fact, we have two choices to overcome this. One way is to encode our string replacing all invalid characters with escape sequences; and decoding it on deserialization. Our second choice, which we are concerned about in this entry, is to serialize the string field into a string enclosed within XML CDATA section which looks like this:  <script><![CDATA[function matchwo(a,b){}]]></script>

To go the CDATA way, we define the string field of our object as XmlCDataSection:

class  MyObject {

public XmlCDataSection myString;


Then we will assign our string to the XmlCDataSection field as follows:  myObject.myString = new XmlDocument.CreateCDataSection(“My string >”);

The literal string “My string >” will now be enclosed in a CDATA section which is ignored by the XML parser


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: