System.Xml.XmlWriter provides an easy and lightweight way to write xml strings, unfortunately it has a little gotcha. consider the following xml string (borrowed from IronPython in Action):
Using XmlWriter the following code is needed to create that string:
Keep in mind the fact that the code above only creates 5 lines of xml, and as you can probably tell it has a very distinct overhead – for each element/document created you must add a WriteEndX statement, the code quickly becomes unreadable and could create an invalid xml string if a WriteEndElement is misplaced or forgotten.
It occurred to me that closing an xml element should not be different from closing a resource which led me to think about using the trusted .NET IDisposable interface:
AutoCloseNote is a simple class that implements IDisposable and run a predefined action when disposed.
AutoCloseXmlWriter has similar methods to the XmlWriter class (I’ve only implemented two in this example) and returns a AutoCloseNode that will run the "WriteEndX method on disposing.
And now we can transform the code from the beginning of the post to this:
We got rid of the need to remember when to call the end element method and we got indentation of our code according to the xml string it represents free of charge.
As you can see we can use this neat trick to create a (more) readable code, do you know of any other examples? (hint: Typemock Isolator)
Labels: .NET, C#, Tips and Tricks