Yossi Dahan [BizTalk]

Google
 

Sunday, December 17, 2006

Serialisation, inheritance and XmlInclude

I keep forgetting this very elegant approach, so here's a note -

When you attribute a member for serialization you can specify the types this member would serialize to using the XmlIncludeAttribute.

When is this useful? - in many cases you will need to use it when you have inheritance implemented.

Consider these two scenarios -

Scenario 1 - you have two classes (x and y) that inherit from a base class b.
you declare a web method that returns b. if you just run the web method and return x or y, any members of the classes that are not declared in b will not get serialized. this is because the XmlSerializer uses the type definition of b to decide how the serialized output should look like.
Add an XmlInclude attribute to you method specifying the two additional types required and the result will get serialized ok.

Scenario 2 - using the same inheritance model (classes x,y and b) you have a fourth class (z) that has a member of type b, at some point you want to seralize an instance of this class, knowing that b can actually contain an object of type x or y.

Again, without the XmlInclude attribute, if you serialize an instance of the class z only field of class b will get serialized for that member. fields of x and y will not get serialized. adding the XmlInclude instructs the serializer to look at these types as well.

and you can see a nice example here

1 Comments:

  • Cheers mate, just solve a "scenario 2" problem I had encountered.

    Thanks for posting.

    By Anonymous Anonymous, at 26/09/2011, 11:13  

Post a Comment

<< Home