How XML serialization of a child class with its base class

I can serialize one type / class, but is there any way that I can serialize its base class as well?

For example:

class B:A 

Here I can serialize class B, but how can I serialize class A?

+7
source share
2 answers

A must know in advance, i.e.

 [XmlInclude(typeof(B))] public class A {...} public class B {...} 

Now new XmlSerializer(typeof(A)) can serialize A or B You can also do this without attributes by passing the extraTypes parameter extraTypes overloaded XmlSerializer constructor, but again - the root should be A ; those. new XmlSeralializer(typeof(A), new[] {typeof(B)})

+8
source

Your question is very vague.

You can simply pass your object to the base class during serialization, however you need to provide subtypes that A can take when creating the serializer ( new XmlSerializer(typeof(MyClass), ExtraTypesGoHere); ), or you use [XmlInclude(Type type)] into classes that may have properties that expose objects of these subtypes.

+1
source

All Articles