Home / Asp .Net / How to create XML in asp dotnet
How to create XML in asp dotnet

We all aware about XML (Extensible Markup Language), it's designed to store and transport data. XML is easy to understand,read and also platform independent. Sometimes we need to create XML file in any programming language, In this post i will show you a simple example how we can create XML file programmatically in asp.net. You can also download code file of this example with database structure.


Front End

<form id="form1" runat="server">
 <div>
     <asp:Button ID="cxml" Text="CREATE XML" runat="server"  OnClick="cxml_Click" />
   <br />
      <asp:Label ID="label1" Text="" runat="server"></asp:Label>
   <br />
 </div>
</form>

 

Code behind

protected void cxml_Click(object sender, EventArgs e)
{
 SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=mydb;Integrated Security=true;");
 using (SqlCommand cmd = new SqlCommand("SELECT * FROM Country_Master", con))
 {
 DataTable dt = new DataTable();
 using (SqlDataAdapter da = new SqlDataAdapter(cmd))
 {
  da.Fill(dt);
  if (dt.Rows.Count > 0)
  {
   using (XmlWriter xWr = XmlWriter.Create(Server.MapPath("country.xml")))
   {
     xWr.WriteStartDocument();
     xWr.WriteStartElement("World");
     for (int i = 0; i < dt.Rows.Count; i++)
     {
       xWr.WriteStartElement("Countries");
       // ADD ELEMENTS.
       xWr.WriteElementString("CountryCode", "" + dt.Rows[i]["Country_Code"] + "");
       xWr.WriteElementString("CountryName", "" + dt.Rows[i]["Country_Name"] + "");
       xWr.WriteEndElement(); // CLOSE LIST.
     }
     xWr.WriteEndElement();          // CLOSE LIBRARY.
     xWr.WriteEndDocument();         // END DOCUMENT.

     // FLUSH AND CLOSE.
     xWr.Flush();
     xWr.Close();

    label1.Text = "Xml File created.";
    }
      con.Close();
   }
  }
 }
}