Serializing A String Within a CDATA Element (.NET 1.1)

Apparently .NET 2.0 does this out of the box but, I don’t get to play with it for awhile so….

Today I had the need to serialize some error messages in CDATA elements. Quickly, I realized that XmlSerializer doesn’t support this out of the box. After a really quick googlin’ session, I had my solution. And since I’m nice, I’ll share it with y’all.

Say you have a class called ErrorMessage that has a string to be serialized:

[Serializable]

public class ErrorMessage

{

private string message; 

….

[XmlElement("message")]

public string Message

{

get { return message; }

set { message = value; }

}

….

}

If you want to inject the message into a CDATA element do the following:

Create a class to hold your CDATA string and implement IXmlSerializable.

public class CDATA : IXmlSerializable

{

private string text;

public CDATA()

{}

public CDATA(string text)

{

this.text = text;

}

public string Text

{

get { return text; }

}

XmlSchema IXmlSerializable.GetSchema()

{

return null;

}

void IXmlSerializable.ReadXml(XmlReader reader)

{

this.text = reader.ReadString();

}

void IXmlSerializable.WriteXml(XmlWriter writer)

{

writer.WriteCData(this.text);

}

}

And change your original ErrorMessage class to

[Serializable]

public class ErrorMessage

{

private CDATA message; 

….

[XmlElement("message", Type=typeof(CDATA))]

public CDATA Message

{

get { return message; }

set { message = value; }

}

….

}

Nice and simple.

This article is part of the GWB Archives. Original Author: Chris Martin

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.