Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Serialize List of Descendants

I am trying to serialize a list of descendants. This is what I have now, that works fine:

class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}

[XmlRootAttribute("Zoo")] 
class Zoo
{
    [XmlArrayItem(typeof(Zebra))]
    [XmlArrayItem(typeof(Hippo))]
    public List<Animal> Actions
    { set; get; }
}

This works fine and I can serialize both Animals. I wonder If it is possible to create an Attribute class where I can pass the list of animals (instances), and will create for me the XmlArrayItems attributes.

In general, I am looking for a way to avoid specifying the descendants of Animal everytime I create a new one. I want all descendants of Animal to be serialized, whatever their type.

like image 628
Odys Avatar asked Jan 01 '12 13:01

Odys


1 Answers

You can get a list of derived types within an assembly like so:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
    var types = Assembly.GetAssembly(type).GetTypes();
    return types.Where(t => t.IsSubclassOf(type));
}

Perhaps you can cycle through a foreach loop on the GetAllTypesDerivedFrom method above, and then fit it into a solution similar to the MSDN example for XmlArrayItems.

NOTE: If you need to get all derived types for an interface, you'll instead need to use the following (would work with both interfaces and classes):

return types.Where(type.IsAssignableFrom).Where(t => t != type);
like image 118
Jason Down Avatar answered Sep 27 '22 19:09

Jason Down