Mega Code Archive

 
Categories / C# Tutorial / XML
 

Using XmlReader to read Xml result set from database

using System; using System.Data; using System.Data.SqlClient; using System.Xml; public class DirectXML {     private static string connectionString = "Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI";     public static void Main()      {         string SQL = "SELECT CategoryID, CategoryName, Description FROM Categories FOR XML AUTO";         SqlConnection con = new SqlConnection(connectionString);         SqlCommand com = new SqlCommand(SQL, con);         try         {             con.Open();             XmlReader reader = com.ExecuteXmlReader();             while (reader.Read())             {                 Console.WriteLine(reader.Name);                 if (reader.HasAttributes)                 {                     for (int i = 0; i < reader.AttributeCount; i++)                     {                         reader.MoveToAttribute(i);                         Console.Write(reader.Name + ": " + reader.Value);                     }                     reader.MoveToElement();                 }             }             reader.Close();         }         catch (Exception err)         {             Console.WriteLine(err.ToString());         }         finally         {             con.Close();         }     } }