Convert the result from a query to XML and output : ResultSet to Xml : ADO.Net C# Examples


C# Examples » ADO.Net » ResultSet to Xml »

 

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);
                                                }
                                        }
                                }
                        }
                }
        }
}
    
   
  
   




HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo ADO.Net
» ResultSet to Xml