Chris McCall
Chris McCall

Reputation: 10407

Providing serialization services in a base class that can be used in derived classes

I've implemented a data access library that allows devs to mark up their derived classes with attributes to have them mapped directly to stored procedures. So far, so good. Now I'd like to provide a Serialize() method or override ToString(), and have the derived classes get free serialization into XML.

Where should I start? Will I have to use Reflection to do this?

Upvotes: 2

Views: 167

Answers (3)

Jeff Yates
Jeff Yates

Reputation: 62407

XML Serialization using XmlSerializer

In the first instance, I would look at the XML Serialization in the .NET Framework that supports serialization of objects to and from XML using an XmlSerializer. There's also an article from Extreme XML on using this serialization framework.

The following links all provide examples of using this approach:

ISerializable and SerializableAttribute

An alternative to this would be to use a formatter and the regular SerializableAttribute and ISerializable system of serialization. However, there is no built-in XML formatter for this framework other than the SoapFormatter, so you'd need to roll your own or find a third party/open source implementation.

Roll Your Own

Also, you could consider writing your own system using, for example, reflection to walk your object tree, serializing items according to their serialization visibility, which could be indicated by your own attributes or the existing DesignerSerializationVisibility attributes. The downside to this shown by most implementations is that it expects properties to be publicly read/write, so bear that in mind when evaluating existing custom solutions.

Upvotes: 2

James Conigliaro
James Conigliaro

Reputation: 3827

You should be able to use the XmlSerializer to perform the serialization of your class

XmlSerializer serializer = new XmlSerializer(this.GetType()); serializer.Serialize(stream, obj);

Upvotes: 1

Eric Petroelje
Eric Petroelje

Reputation: 60549

I would start by looking at XmlSerializer.

Hopefully you'll be able to end there too, since it already gives you this functionality :)

Upvotes: 1

Related Questions