How to serialize a derived class as a base class

I have a derived class that only adds methods to the base class. How to serialize a derived class so that it matches the serialization of the base class? those. The serialized xml of the derived class should look like this:

<BaseClass> ... </BaseClass> 

eg. The following will throw an InvalidOperationException "DerivedClass type was not expected. Use the XmlInclude or SoapInclude attribute to indicate types that are not statically known."

 Class BaseClass {} Class DerivedClass : BaseClass {} DerivedClass derived = new DerivedClass(); StreamWriter stream = new StreamWriter("output file path"); XmlSerializer serializer = new XmlSerializer(GetType(BaseClass)); serializer(stream, derived); 
+6
serialization
source share
4 answers

You need to pass GetType (DerivedClass) to the serializer constructor, it must match the type of object you are serializing. You can use the <XmlRoot> attribute to rename to the root element. This sample 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 { } 
+4
source share

You can also implement the ICloneable interface for BaseClass, and then do:

 var sw = new StringWriter() var base = (derived as BaseClass).Clone() var serializer = new XmlSerializer(typeof(BaseClass)) serializer.Serialize(sw, base) Console.WriteLine(sw.ToString()) 

Not an ideal approach, but if your base class is simple, it should work as well.

+1
source share

I have not tried it, but can you just drop it?

 serializer(stream, (BaseClass)derived); 

Edit

In addition, if you want to have one XmlSerialiser that can handle several derived classes and a base class, then you need to specify all types in the XmlSerialiser constructor.

  XmlSerializer serializer = new XmlSerializer(typeof(BaseClass), new Type[] {typeof(DerivedClass)}); 

Then he will happily serialize several types. However, you will also have to use the solution mentioned above to get the xml output to match between classes.

0
source share

After a bit of googling;) I can say that you need one more code and implement IXmlSerializable for your base class, declaring all the interface methods virtual and overriding them in the derived class. Here is a sample topic and a similar problem on the specified interface.

0
source share

All Articles