BreakHead
BreakHead

Reputation: 10672

How to XML serialize child class with its base class

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 ?

Upvotes: 7

Views: 9358

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062502

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)})

Upvotes: 8

brunnerh
brunnerh

Reputation: 184296

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.

Upvotes: 1

Related Questions