FOR XML Needs More Love

I’m constantly amazed by the number of developers who have never worked with FOR XML EXPLICIT and the new FOR XML PATH.  If I were designing data access, it would be my go-to commands for building queries for complex data structures (nested DataReaders?  yuck!).

In the past, to support paging using FOR XML EXPLICIT queries took tons of lines to accomplish (although there is something about the whole explicitness that makes it surprisingly legible).  Now with the fancy pants ROW_NUMBER function in SQL along with CTEs, a hundred line query can be written with maybe 15-20 lines.

Here’s a simple example that you can copy+paste and run:

What’s great about this is that if your object model is properly designed, it’s just a matter of deserializing the XML (using precompiled serialization binaries, of course) to rehydrate your data model.

In this case, the output XML looks like this:

Next, you’ll need some simple code to deserialize the XML to make it useful:

It might even be useful to add some abstract methods (and properties to support it) to GetNextPage()

You may also like...