Using XmlReader with SQL Server’s FOR XML AUTO in ASP.NET 2.0
Author: Aadil
This article will show how to use the xml based XmlReader object with ADO.NET to access the data in xml format.
If you have previously worked with ADO.NET then you must have used a kind of DataReader for a forward only read only very fast access to the data source. All the data providers contain an object that implements the IDataReader interface to support the basic DataReader implementation. Such as the .NET SQL Server data provider that resides in the System.Data.SqlClient namespace contains the SqlDataReader that is a DataReader for Microsoft SQL Server.
A DataReader is used for accessing the queried data as a fast, forward only, read only cursor. You can read the data from this object and display in any page using the same techniques as the classic ASP’s Recordset object.
SQL Server provides you with ways to access the data natively in XML format. A similar technique for accessing this data as xml is to use the FOR XML AUTO clause. When you specify this clause in the SQL statement, you can call the command object’s ExecuteXmlReader method to get an object of type XmlReader. This method is a new addition in the .NET Framework version 2.0 and the class XmlReader is present in the System.Xml namespace.
There are a lot of methods and properties present in this object for working with xml typed data. I’ve created a sample function that queries and displays the data just as the SqlDataReader except in this case I’ve used the new XmlReader object. Here is the code.