ExecuteXmlReader Example In Asp.Net C# VB.Net

This example explains how to use ExecuteXmlReader Method In Asp.Net Using C# And VB

You may also read how to use NonQuery, Reader and ExecuteScalar Methods of SqlCommand.

This method executes the command and builds XmlReader, for it to work with fetching database records we need to use FOR XML AUTO clause in sql query.

C# CODE
01string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
02        string strSelect = "SELECT Username,Password FROM Users FOR XML AUTO";
03 
04        SqlConnection con = new SqlConnection(strConnection);
05        SqlCommand cmd = new SqlCommand(strSelect, con);
06 
07        con.Open();
08        XmlReader reader = cmd.ExecuteXmlReader();
09        reader.Read();
10        XmlDocument doc = new XmlDocument();
11        doc.Load(reader);
12        doc.Save("test.xml");
13        reader.Close();
14        con.Close();

VB.NET
01Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
02Dim strSelect As String = "SELECT Username,Password FROM Users FOR XML AUTO"
03 
04Dim con As New SqlConnection(strConnection)
05Dim cmd As New SqlCommand(strSelect, con)
06 
07con.Open()
08Dim reader As XmlReader = cmd.ExecuteXmlReader()
09reader.Read()
10Dim doc As New XmlDocument()
11doc.Load(reader)
12doc.Save("test.xml")
13reader.Close()
14con.Close()

If you like this post than join us or share

0 comments:

Find More Articles