Today, while doing some work on a highly data (not object) driven .NET application, I needed a query output as XML from the application's SQL Server 2005 database. I wanted:
- Nicely formatted and properly mapped XML (e.g. no
elements as found in FOR XML RAW mode)
- To be able to easily map columns to XML elements and attributes
- A single root node, so I can load it into an XmlDocument without having to create the root node myself
- Nested child elements
- Not to have to turn my elegant little query into a huge mess of esoteric T-SQL (as with [Explicit!1!Mode])
I discovered that all this is surprisingly easy to achieve all of these things with SQL Server 2005's FOR XML PATH mode. (I say surprising, because I've tried this sort of thing with FOR XML AUTO a few times before under SQL Server 2000, and gave up each time).
Here's a quick example I've created using the venerable AdventureWorks example database, with comments against all the important bits:
As you can see, we've mapped columns to attributes/elements with XPath selectors, and set row and root element names with PATH() and ROOT() respectively.
Plus, by specifying my own names for everything, I was also able to address the difference in capitalization, prefixing and pluralization style between the AdventureWorks' database table names and common XML.
Running this query produces output in the following format. Note the root nodes for both outer and child collections:
You can read more about using FOR XML PATH here.