How to deserialize an XML array containing multiple types of elements in C#
There are two ways to do this; the first is to do something like:
[XmlArray("players")][XmlArrayItem("skater", Type=typeof(Skater))][XmlArrayItem("goalie", Type=typeof(Goalie))]public List<SomeCommonBaseClass> Players { get; set; }
which maps the two element types inside a single collection. Worst case, SomeCommonBaseClass
could be object
:
[XmlArray("players")][XmlArrayItem("skater", Type=typeof(Skater))][XmlArrayItem("goalie", Type=typeof(Goalie))]public List<object> Players { get; set; }
The second is to make <players>
map to a wrapper object:
[XmlElement("players")]public Players Players { get;set;}...public class Players{ [XmlElement("skater")] public List<Skater> Skaters {get;set;} [XmlElement("goalie")] public List<Goalie> Goalies {get;set;}}
Which to choose depends on the circumstance; the latter allows things like "at most one goalie", by changing it to:
[XmlElement("goalie")] public Goalie Goalie {get;set;}