I have a XML document that several cases of specialization of entries, I managed to get a solution from here to deserialize it . I have done the exact same of the example and works as a charm, however It only works if a single specialized class appears. In the links example(shown above), imagine there is another class specialized from Instrument (for example, Drums). How can I use this method to tell the deserializar when to cast to each of the specialized classes?
Serialized object:
public class Orchestra
{
public Instrument[] Instruments;
}
public class Instrument
{
public string Name;
}
public class Brass:Instrument
{
public bool IsValved;
}
Example of deserialization:
public void DeserializeObject(string filename)
{
XmlAttributeOverrides attrOverrides =
new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
// Create an XmlElementAttribute to override the Instrument.
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "Brass";
attr.Type = typeof(Brass);
// Add the XmlElementAttribute to the collection of objects.
attrs.XmlElements.Add(attr);
attrOverrides.Add(typeof(Orchestra), "Instruments", attrs);
// Create the XmlSerializer using the XmlAttributeOverrides.
XmlSerializer s =
new XmlSerializer(typeof(Orchestra), attrOverrides);
FileStream fs = new FileStream(filename, FileMode.Open);
Orchestra band = (Orchestra) s.Deserialize(fs);
Console.WriteLine("Brass:");
/* The difference between deserializing the overridden
XML document and serializing it is this: To read the derived
object values, you must declare an object of the derived type
(Brass), and cast the Instrument instance to it. */
Brass b;
foreach(Instrument i in band.Instruments)
{
b = (Brass)i;
Console.WriteLine(
b.Name + "\n" +
b.IsValved);
}
}
I have tried adding another attribute override but it does not work, I have also tried making two separate deserializers (each with an attribute override with the property I would like to cast to an object) it neither works as it fails to cast objects of the other type resulting in an type exception.
Any ideas?