views:

101

answers:

3

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?

+1  A: 

I would start by looking at XmlSerializer.

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

Eric Petroelje
+2  A: 

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.

Jeff Yates
+1  A: 

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

James Conigliaro