Xml Serialize List of Descendants
Asked Answered
J

1

7

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.

Juan answered 1/1, 2012 at 13:15 Comment(0)
B
4

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);
Bourguiba answered 1/1, 2012 at 14:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.