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.