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
string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strSelect = "SELECT Username,Password FROM Users FOR XML AUTO";
        
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand(strSelect, con);
        
        con.Open();
        XmlReader reader = cmd.ExecuteXmlReader();
        reader.Read();
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        doc.Save("test.xml");
        reader.Close();
        con.Close();

VB.NET
Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim strSelect As String = "SELECT Username,Password FROM Users FOR XML AUTO"

Dim con As New SqlConnection(strConnection)
Dim cmd As New SqlCommand(strSelect, con)

con.Open()
Dim reader As XmlReader = cmd.ExecuteXmlReader()
reader.Read()
Dim doc As New XmlDocument()
doc.Load(reader)
doc.Save("test.xml")
reader.Close()
con.Close()

If you like this post than join us or share

0 comments:

Find More Articles