I will simplify the code to save space but what is presented does illustrate the core problem.
I have a class which has a property that is a base type. There are 3 d
I had the same issue and some Googling lead me here. I could not accept to have the XMLInclude
attribute for each implementation in the base class. I got it to work with a generic serialization method. First off, some of the OP's original example, but slightly modified for clarity:
public abstract class PaymentSummary
{
public string _summary;
public string _type;
}
public class xPaymentSummary : PaymentSummary
{
public xPaymentSummary() { }
public xPaymentSummary(string summary)
{
_summary = summary;
_type = this.GetType().ToString();
}
}
In addition to the above, there is also a yPaymentSummary
and zPaymentSummary
with exactly the same implementation. These are added to a collection, and then the serialization method can be called on each:
List summaries = new List();
summaries.Add(new xPaymentSummary("My summary is X."));
summaries.Add(new yPaymentSummary("My summary is Y."));
summaries.Add(new zPaymentSummary("My summary is Z."));
foreach (PaymentSummary sum in summaries)
SerializeRecord(sum);
Finally, the serialization method - a simple generic method, that uses the Type of record when serializing:
static void SerializeRecord(T record) where T: PaymentSummary
{
var serializer = new XmlSerializer(record.GetType());
serializer.Serialize(Console.Out, record);
Console.WriteLine(" ");
Console.WriteLine(" ");
}
The above yields the following output: