Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

FREE 12 month online training for ASP.NET & MS Expression Studio and a Free copy of MS Expression Web with Windows Server Purchase
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.

 

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

    Dim objConn As New SqlConnection(ConfigurationManager.ConnectionStrings("db2ConnectionString").ConnectionString)

    objConn.Open()

   

    Dim objCmd As New SqlCommand("select * from employees for xml auto", objConn)

    Dim xr As System.Xml.XmlReader = objCmd.ExecuteXmlReader()

    Response.Write("List of All Employee Names

"
)

    While xr.Read

      Response.Write(xr("ename") & "
"
)

    End While

    xr.Close()

    xr = Nothing

    objCmd.Dispose()

    objCmd = Nothing

   

    objConn.Close()

    objConn = Nothing

  End Sub
   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Creating a Web Services Using ASP.Net

Disclaimer - Privacy
© 2002-2012 DevASP.net