Developing for Modern Windows

Tips, tricks, and guides for developing on modern Windows platforms

Serializing Sub-Classes in XML

I recently came upon a problem when serializing a class to XML using my standard serializing technique. It wouldn’t serialize a list of Vehicle objects:

List<Vehicle> vehiclesList { get; set; }

This gave an error message like this:

 

“The type App1.Motorcycle was not expected. Use the XmlInclude attribute to specify types that are not known statically.”

Unfortunately the error message and suggested remedy do not lead to the solution…

The Cause

The cause of the failure to serialize was that vehiclesList actually contained various types that inherited Vehicle, but their actual types were Car, Motorcycle, Bus, etc. The XML serializer in WinRT couldn’t handle this. Once I figured this out I tracked down the solution:

 

The Solution

You need to tell the XML serializer what subclasses to expect so it can write out the correct types.

Add a list of the possible types as XmlArrayItems above the declaration for the list, like this:


[XmlArrayItem(typeof(Car)),
XmlArrayItem(typeof(Motorcycle)),
XmlArrayItem(typeof(Bus)),
XmlArrayItem(typeof(Truck)),
XmlArrayItem(typeof(Batmobile))]
public List<Vehicle> vehiclesList{ get; set; }

Now the serializer knows what types to expect in the list when it does its work!

Tags: ,

Leave a Reply

Your email address will not be published.