Friday, April 8, 2011

Fetching Data from a Database in XML Format

Here we will see that how can we fetch data from database in XML format.
using System;
using System.Data.SqlClient;
using System.Xml;

namespace test
{
          /// <summary>
          /// Summary description for Class1.
          /// </summary>
          class ReadXML
          {
                    /// <summary>
                    /// The main entry point for the application.
                    /// </summary>
                    [STAThread]
                    static void Main(string[] args)
                    {
                             //
                             string connectionString = "server=.;uid=test;pwd=test;database=test";
                             SqlConnection con = new SqlConnection(connectionString);
                             SqlCommand cmd = new SqlCommand("select * from test for xml auto, elements", con);
                             con.Open();
                             XmlReader reader = cmd.ExecuteXmlReader();
                             con.Close();
                             XmlDocument doc = new XmlDocument();
                             doc.LoadXml("<root></root>");
                             XmlNode node = doc.ReadNode(reader);
                             while(node != null)
                             {
                                       Console.WriteLine(node.InnerXml);
                                       node = doc.ReadNode(reader);
                             }

                             reader.Close();
                             reader = null;
                             doc = null;
                             //
                    }
          }
}

No comments:

Post a Comment