Use the XmlInclude or SoapInclude attribute to specify types that are not known statically
This worked for me:
[XmlInclude(typeof(BankPayment))]
[Serializable]
public abstract class Payment { }
[Serializable]
public class BankPayment : Payment {}
[Serializable]
public class Payments : List<Payment>{}
XmlSerializer serializer = new XmlSerializer(typeof(Payments), new Type[]{typeof(Payment)});
Just solved the issue. After digging around for a while longer, I found this SO post which covers the exact same situation. It got me in the right track.
Basically, the XmlSerializer
needs to know the default namespace if derived classes are included as extra types. The exact reason why this has to happen is still unknown but, still, serialization is working now.
Base on this I was able to solve this by changing the constructor of XmlSerializer
I was using instead of changing the classes.
Instead of using something like this (suggested in the other answers):
[XmlInclude(typeof(Derived))]
public class Base {}
public class Derived : Base {}
public void Serialize()
{
TextWriter writer = new StreamWriter(SchedulePath);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>));
xmlSerializer.Serialize(writer, data);
writer.Close();
}
I did this:
public class Base {}
public class Derived : Base {}
public void Serialize()
{
TextWriter writer = new StreamWriter(SchedulePath);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>), new[] { typeof(Derived) });
xmlSerializer.Serialize(writer, data);
writer.Close();
}