May 2, 2012

XmlSerializer Usage

C# Tutorial - XML Serialization

Watch out for derived classes, the Xml serializer will not know how to serialize them without being told about them.
For example, a base class is "MenuItemDefinition"
Derived classes are "StartExecutableMenuItem", "RestartExecutableMenuItem"
To serialize instances of the base class, create an XmlSerializer thus:
XmlSerializer serializer = new XmlSerializer(
  typeof(List<MenuItemDefinition>),   // Object type to serialize
  // Following list of types are derived class types that the 
  // XmlSerializer will need to know about to perform the serialization
  new Type[] { typeof(StartExecutableMenuItem), typeof(RestartExecutableMenuItem), });
so here is the full serialization:
private void MenuItemsSerialize()
{
    IEnumerable<MenuItemDefinition> menuItems = LoadMenuItemDefinitions();
    var li = new List<MenuItemDefinition>();
    li.AddRange(menuItems);

    XmlSerializer serializer = new XmlSerializer(
      typeof(List<MenuItemDefinition>), // Object type to serialize
      // List of types that are derived class types that the 
      // XmlSerializer will need to know about to perform the serialization
      new Type[] { 
        typeof(StartExecutableMenuItem), 
        typeof(RestartExecutableMenuItem), }
    );
    string path = Path.Combine(Path.GetTempPath(), "delme.xml");
    TextWriter textWriter = new StreamWriter(path);
    serializer.Serialize(textWriter, li);
    textWriter.Close();
}
Alternatively a bunch of XmlInclude attributes on the base class will do the job.

No comments: