As you might have guessed it I work on a lot in the XML namespace of .NET and I’m finally starting to use some of the new XmlReader features.  This post will go over some of them here.  And remember a wise man once said that everything can be solved with one more layer of abstraction.  These new features are nothing more than an encapsulation of code that the major of us have written thousands of times before but its all about productivity.  Why just today I was at a meeting going over some change requests and noticed that n new features were being added and schedule and budget remained constant.  🙂

.ReadToFollowing(string)  This method will forwards the cursor and returns a true once the conditions of the XmlNodeType.Element and Name equals your parameter.  This is very useful for crawling through large files where you only require a small amount of data from.

.ReadToNextSibling(string)  This method is great for splitting out smaller Xml messages that are inside of a larger schema since it will return true once the next sequential sibling is matched.  Example is here:

do{

//do your stuff...

}while(reader.ReadToNextSibling("foo"));

I use this one often in doing my own disassembly in helper classes.

.ReadSubTree() This method actually returns a XmlReader with limited scope of the subtree.  It does this by the use of an internal class called the XmlSubTreeReader which basically uses a reader to .MoveToElement() until the initial depth of that subtree has been met.  This saves me heaps of time instead of my usual mess of climbing down into each subtree manually.  I’ve always thought that writing code that read Xml was never elegant since Xml is so flexible.  Something had to give.

.ReadElementContentAsXxx() Now there are a bunch of these methods one for each type (doubles, int32s, strings, etc.)  and they are great because we no longer have to cast the value out of the XmlReader.  Each different method has an underlying class that specifically handles extracting the contents out of a Node with casting which can be expensive.

.Create() This is probably my favorite one.  So how many times have we called XmlReader reader = new XmlReader();?  Well now the Xml team has taken a lesson from the Enterprise Library folks in giving us a Factory Pattern for creating new instances of an XmlReader.  XmlReader reader = XmlReader.Create() several overloads exist for this.  So much easier than before.  Love the factory pattern.

Now this is just a small amount of what changed in the XML namespace in 2.0.  Overall performance has improved 20-30% on average (especially with compile XSLT).  These are also were BizTalk 2006 has picked up most of its performance gains over its predecessors.  Also its worth reading this by Aaron Skonnard on the new features of XML 2.0.