Tuesday, June 3, 2014

Insert Data/Record in XML File Using C#.Net

Hi friends, 
Today I am going tell you that how can we insert data/record in xml file using c# code in .net. I will be explaining all these step one by one. You can also download source code from there download.

Step 1- Create new project to your visual studio and give name of this project is xmlinsertdata.
Step 2- Add new page  xml.aspx in your project and added some textbox field to this page.
Step 3-On buttonclick vent write this code.
protected void cmdsave_Click(object sender, EventArgs e)
    {
        XmlTextWriter xWriter = new XmlTextWriter(HttpContext.Current.Server.MapPath("~/App_Data/" + "EmployeeDetails.xml"), Encoding.UTF8);
        xWriter.WriteStartDocument();
        xWriter.WriteStartElement("EmployeeDetails");
       
            xWriter.WriteStartElement("Details");
            xWriter.WriteAttributeString("Name", txtname.Text.Trim().ToString());
            xWriter.WriteElementString("Qualification", txtqual.Text.Trim().ToString());
            xWriter.WriteElementString("Address", txtadd.Text.Trim().ToString());
            xWriter.WriteElementString("Description", txtdesc.Text.Trim().ToString());
  
             xWriter.WriteEndElement();

      
        xWriter.WriteEndElement();
        xWriter.WriteEndDocument();
        //End writing top element and XML document

        xWriter.Close();
    }

Use System.Xml; namespace for  XmlTextWriter  class.and System.Text name space for Encoding  class.


Screenshot for this snippet is-

No comments:

Post a Comment