Monday, February 6, 2012

Generating XML file in ASP.Net


Create XML file from database

The code will generate XML file in your local drive by fetching data from your sqlserver database. Just edit your connection scting and put the below code within any event of ASP.Net page.

insert the namespaces

using System.Xml;
using System.Data.SqlClient;

public partial class loadxml : System.Web.UI.Page
{

SqlConnection con = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
         string query;

        SqlDataReader rd;
        cmd.CommandText = "select * from loginfo";
        rd = cmd.ExecuteReader();


        XmlDocument writer = new XmlDocument();
        XmlNode declaration =    writer.CreateNode(XmlNodeType.XmlDeclaration, null, null);
        writer.AppendChild(declaration);

        XmlElement root = writer.CreateElement("person");
        writer.AppendChild(root);

        while (rd.Read())
        {
string user = rd.GetSqlValue(0).ToString();
          string pass = rd.GetSqlValue(1).ToString();
          string id =  rd.GetSqlValue(2).ToString();
           
            XmlElement person1 = writer.CreateElement(id);
            root.AppendChild(person1);

            XmlElement name = writer.CreateElement("name");
            name.InnerText = user;
            person1.AppendChild(name);


            XmlElement surname = writer.CreateElement("surname");
            person1.AppendChild(surname);
            surname.InnerText = pass;
           
        }
        rd.Close();
        con.Close();

       writer.Save("D:\\sourav.xml");
}

Output:-
<person>
<user>sourav</user>
<pass>kayal</pass>
<id>1</id>
</person>



No comments:

Post a Comment