Cleaning up XmlWriter and IXmlSerializable with Extension Methods

by jmorris 4. November 2009 19:46

If you do any work with xml you probably have come across scenarios where you are using an XmlWriter to produce an output stream of xml. Eventually this output stream is either persisted to disk via an XDocument, sent over the wire using a distributed technology such as WCF, Remoting etc., or possibly transformed with XSL/XSLT. A strong example is custom serialization classes that implement IXmlSerializable.  For example:

The class above is a simple data transfer class (DTO) that implements IXmlSerializable so that it can be serialized and/or deserialized from an objet to an xml stream and vice versa. Note: in most cases you would simple mark the class as [Serializable] and/or provide attributes from the System.Xml namespace to provide the same behavior, however in many cases the default implemention will not fit your particular scenario, hence you would implement IXmlSeriable and provide your own custom serialization.

Here is the 'custom' serialization implementation:


While the XmlWriter/XmlReader API's are pretty simple to use, they are also a bit verbose. If you happen to have a fairly large class with many fields, things start to get ugly pretty fast. Typically when I see large classes, I began to think about refactoring into smaller classes when applicable, but that not always the case. Since, most of them time when want serialization/deserialization you simple want to quickly (i.e. less keystrokes) turn the contents and structure of the class into its xml equivalent you are looking at reducing the amount of work needed. This is where extension methods really come in handy:



The result compared to above is a much cleaner, easier to read class:


While extension methods are not new, they do offer unique way of handling situations where you would like to simplify a set of operations without reaching for the traditional static xxxUtil class or creating a customized implementation or wrapper class. In this case,  XmlWriter is a class open for extension via basic inheritance, unlike a sealed class such as System.String, which is the intended purpose of extension methods: extended classes closed to inheritance (sealed).

Tags: , , , , , , ,

Comments (2) -

Network Consulting
Network Consulting
4/22/2011 2:47:51 PM #

But mostly you would simple mark the class as serializable and provide attributes from the System.Xml namespace to provide the same behavior.

Neiko
Neiko
4/25/2011 4:00:45 PM #

I like this clean approach, but was hoping to see the deserialize version of it too. Since Framework 3.5 you can also use WriteElementString(xmlTagName, string)

msdn.microsoft.com/de-de/library/aex0e7zs.aspx

Jeff Morris

Tag cloud

Month List

Page List