Mega Code Archive

 
Categories / C# Tutorial / ADO Net
 

Convert the result from a query to XML and output

using System; using System.Xml; using System.Data; using System.Data.SqlClient; class MainClass {     public static void Main(string[] args)     {         using (SqlConnection con = new SqlConnection()) {             con.ConnectionString = @"Data Source = .\sqlexpress;Database = Northwind; Integrated Security=SSPI";             using (SqlCommand com = con.CreateCommand()) {                 com.CommandType = CommandType.Text;                 com.CommandText = "SELECT ID, FirstName" +                     " FROM Employee FOR XML AUTO";                 con.Open();                 using (XmlReader reader = com.ExecuteXmlReader())                 {                     while (reader.Read())                     {                         Console.Write("Element: " + reader.Name);                         if (reader.HasAttributes)                         {                             for (int i = 0; i < reader.AttributeCount; i++)                             {                                 reader.MoveToAttribute(i);                                 Console.Write("  {0}: {1}",                                     reader.Name, reader.Value);                             }                             reader.MoveToElement();                             Console.WriteLine(Environment.NewLine);                         }                     }                 }             }         }     } }