Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to XML serialize child class with its base class

Tags:

c#

.net

I am able to serialize a single type/class but is there a way that I can serialize it base class too?

For example:

class B:A

Here I am able to serialize class B but how can I serialize class A ?

like image 584
BreakHead Avatar asked Feb 09 '11 10:02

BreakHead


2 Answers

A must know in advance, i.e.

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


public class B {...}

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

like image 151
Marc Gravell Avatar answered Nov 06 '22 19:11

Marc Gravell


Your question is very vague.

You could just cast your object to the base class when serializing, however when you do that you need to provide the sub-types that A can assume when creating a serializer (new XmlSerializer(typeof(MyClass), ExtraTypesGoHere);), or you use [XmlInclude(Type type)] in the classes that may have properties exposing objects of those sub-types.

like image 34
H.B. Avatar answered Nov 06 '22 17:11

H.B.