How to Write an XML in ASP.NET With SqlDataReader
- 1). Add the following namespaces to the top of the relevant code file:
'using System.Data.SqlClient;
using System.Xml;' - 2). Create new SqlConnection and SqlCommand objects:
'SqlConnection c = new SqlConnection(//insert applicable parameters here);
SqlCommand cm = new SqlCommand();' - 3). Assign the SqlConnection object to the connection property of the SqlCommand object:
'cm.Connection = c;' - 4). Assign a text string containing your SQL query to the "CommandText" property of the SqlCommand:
'c.CommandText = //your query here' - 5). Create a SqlDataReader object and assign it the value of the executed SqlCommand:
'SqlDataReader r = cm.ExecuteReader();' - 1). Create an XmlTextWriter object, using a constructor parameter to reference the data you wish to transform into XML:
'XmlTextWriter w = new XmlTextWriter(//parameter);' - 2). Create a "while" statement using the SQLDataReader as its boolean condition:
'while(r.Read())
{
}' - 3). Use the SqlDataReader to feed data to the XMLTextWriter within the braces of the "while" statement. Start at the first row:
'w.WriteSTartElement("row";
//customize XML here per your requirements'
Retrieving Database Data and Place it into a SqlDataReader
Write the Data from the SQLDataReader in XML Format
Source...