I had to make CronItem
implement the IXmlSerializable
interface, and use the WriteCData
method on the Info
property. Here is the full class:
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace DummyConsoleApp
{
public partial class CronItem : IXmlSerializable
{
public XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("Id", Id.ToString());
writer.WriteElementString("Name", Name);
writer.WriteStartElement("Info");
if (Info != null)
{
writer.WriteCData(Info);
}
writer.WriteEndElement();
}
}
}
This is the full program that calls the serialization process:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DummyConsoleApp
{
class Program
{
static void Main(string[] args)
{
var cronItem = new CronItem
{
Id = 42,
Name = "Bloat",
Info = "gibberish"
};
Console.Write(Serialize(cronItem));
Console.Read();
}
public static string Serialize<T>(T value)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlSerializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
}
}