C# Deserialize XML to a list of ChildClasses



I have a XML from a 3rd party software that I have to deserialize, but I have the spec of the XML.


At a certain point I have a node that contains a bunch of different Nodes of different types. I have to deserialize this Node (Vehicles) as a list. Each of the child nodes is one subclass of the class Vehicle



public List<Vehicle> Vehicles = new List<Vehicles>();


the definition of the class is as following



public class Vehicle
{
public string Vehicletype { get; set; }

public virtual bool Drive() { return true; }
}

public class Car:Vehicle
{
public int NumberOfDoors { get; set; }

public override bool Drive() { return false; }
}

public class Boat:Vehicle
{
public int NumberOfSeats { get; set; }
}


The definition of the XML looks like this



<vehicles>
<car NumberOfDoors="4" />
<car NumberOfDoors="3" />
<boat NumberOfSeats="1024" />
<boat NumberOfSeats="20" />
<car NumberOfDoors="5" />
</vehicles>


At a certain point I have to loop through them and let them "Drive". I don't have the experience With XMLSchema definitions. Now I am using The vehicleType in a factory and some other things. It's basically becoming a mess.


I would need a suggestion how to let the Serializer do this instead of me. I doubt that I am the first one to have this issue.


No comments:

Post a Comment