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?
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
SerializableAttributeandISerializablesystem of serialization. However, there is no built-in XML formatter for this framework other than theSoapFormatter, 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
DesignerSerializationVisibilityattributes. 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.