You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

Serializing abstract classes to XML

Digg it: http://digg.com/programming/Serializing_abstract_classes_to_XML_in_c

It is often useful to have abstract classes with several derived types to allow use of strongly typed lists and the such.

For example you might have a DocumentFragment class which is abstract and two concrete classes called TextDocumentFragment and CommentDocumentFragment (this example from Willis).

This allows the creation of a List<DocumentFragment> property which can contain objects only of those two types.

If you attempt to create a WebService that returns this list you get an error but this is easy to get around with the code below....

[Serializable()]
[System.Xml.Serialization.XmlInclude(typeof(TextDocumentFragment))]
[System.Xml.Serialization.XmlInclude(typeof(CommentDocumentFragment))]
public abstract class DocumentFragment {
...}

The XmlInclude attributes tell the class that it might be serialized to those two derived classes.

This generates an attribute in the DocumentFragment element specifying the actual type, as below.

<DocumentFragment xsi:type="TextDocumentFragment">

Any additonal properties specific to the derived class will also be included using this method.

kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Dave Howard Skype
Author : Dave Howard
Published : Tuesday, 18 July, 2006

I have been involved in IT development for the last 10 years - a lot of it around desktop applications and telecoms.

Comments

Anonymous said:

This is really handy dave, thanks

July 18, 2006 - 9:33 AM

Anonymous said:

This methodology seems to be hiding the true problem and that is an inaccurate implementation of OO design patterns, namely the factory pattern.

Having to change the base class to reference any new factory class is self-defeating.

With a little after-thought, the code can be changed to where any derived type can be associated with the abstract class (through the miracle of interfaces) and no XmlInclude would be required.

I suggest further research into factory patterns which seems to be what you are trying to implement here.

September 26, 2006 - 1:36 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views