XmlWriter that automatically close elements using IDisposable

Saturday, August 01, 2009

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:

Lightbulb - Darren Hester


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)

1 comment

  1. renouncedthoughts.wordpress28 May 2014 at 10:01

    Pretty innovative you got there with the using, and IDisposable. Looks tempting but for my implementation looks a little overkill, so I am defaulting to WriteEndElement.

    But a very good idea embracing the existing c# and .Net constructs. Thanks.


Newer Older
Related Posts Plugin for WordPress, Blogger...