How to serialize a derived class as its base class
You'll have to pass GetType(DerivedClass) to the serializer constructor, it must match the type of the object you serialize. You can use the <XmlRoot>
attribute to rename to the root element. This example code worked as intended:
using System;
using System.Xml.Serialization;
using System.IO;
class Program {
static void Main(string[] args) {
var obj = new DerivedClass();
obj.Prop = 42;
var xs = new XmlSerializer(typeof(DerivedClass));
var sw = new StringWriter();
xs.Serialize(sw, obj);
Console.WriteLine(sw.ToString());
var sr = new StringReader(sw.ToString());
var obj2 = (BaseClass)xs.Deserialize(sr);
Console.ReadLine();
}
}
public class BaseClass {
public int Prop { get; set; }
}
[XmlRoot("BaseClass")]
public class DerivedClass : BaseClass { }