Pages

Tuesday 11 September 2012

How to generate XML File in ASP.Net from SQL Server(Example-2) ?

    I have already discussed about generating XML File from database in my previous article(http://mydotnetcollections.blogspot.in/2012/09/how-to-create-xml-file-from-sql-server.html). Now, I am discussing about generating XML File in another method.
Step-1: Create a Table(Customer) in your Database and add three columns(CustomerID ,Name, Address) to it.
Step-2: Insert some default values to it.

Step-3: Add a Page to your website for generating XML. Also add a button(GenerateXML) to the Page. Add a Namespace- "using System.Xml;".

Step-4: Write these following lines in the button's Click_Event.

protected void GenerateXML_Click(object sender, EventArgs e)
    {
        //***************** Retriving Customer Details From Database ********************//
        SqlConnection con = new SqlConnection("------Your Connection String------");
        SqlCommand com = new SqlCommand("select * from Customer", con);
        SqlDataAdapter da = new SqlDataAdapter(com);
        DataTable dt = new DataTable();
        dt.TableName = "Customers";
        da.Fill(dt);
        XmlTextWriter xml = new XmlTextWriter(Server.MapPath("Customer.xml"), System.Text.Encoding.UTF8);
        xml.WriteStartDocument(true);
        xml.Formatting = Formatting.Indented;
        xml.Indentation = 2;
        xml.WriteStartElement("Customer");
        foreach (DataRow dr in dt.Rows)
        {
            xml.WriteStartElement("CustomerDetails");
            xml.WriteStartElement("CustomerID");
            xml.WriteString(dr[0].ToString());
            xml.WriteEndElement();
            xml.WriteStartElement("Name");
            xml.WriteString(dr[1].ToString());
            xml.WriteEndElement();
            xml.WriteStartElement("Address");
            xml.WriteString(dr[2].ToString());
            xml.WriteEndElement();
            xml.WriteEndElement();
        }
        xml.WriteEndElement();
        xml.WriteEndDocument();
        xml.Close();
    }
Here, I have generated and stored the XML File in the Solution Folder itself. You can give your own Location for saving the generated XML File.
Step-5: Now, Run your webpage and Click the button to generate XML File. After that, an XML File ("Customer.xml") will be generated in your given Folder. In my case it will be stored in my Solution Folder.

The Customer.xml 





Regards,
Prajanuranjan.....

No comments:

Post a Comment

Total Pageviews