Tuesday, 19 July 2011

How to insert data into XML file?


Tags : Insert,Data,XML File,Asp.Net,C#.Net

Hi Friends,in this post i would like to explain how to insert data into XML file.

* Here in my example i am stored Name,Location,Email & Gender fields into XML file.For this i took 3 TextBoxes,DropDownList for Gender,Button & a label for displaying message.

* Added XML file with name(InsertData)
For this Go To SolutionExplorer-->Right Click on ApplicationName-->AddNewItem-->Select XML File-->Give Name as InsertData-->Click on Add button.

Design View :

Source Code :

Default.aspx.cs :
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml;

public partial class _Default : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)


protected void ButtonInsertXML_Click(object sender, EventArgs e)
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;

// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("Name", Server.HtmlEncode(TextBoxName.Text));
myXmlElement.SetAttribute("Location", Server.HtmlEncode(TextBoxLocation.Text));
myXmlElement.SetAttribute("Email", Server.HtmlEncode(TextBoxEmail.Text));
myXmlElement.SetAttribute("Gender", Server.HtmlEncode(DropDownListGender.SelectedItem.Text));

// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);

// Re-bind data since the doc has been added to

LabelMessage.Text = "Record inserted Successfully Inside the XML File...";

TextBoxName.Text = "";
TextBoxLocation.Text = "";
TextBoxEmail.Text = "";


void BindData()
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));


* Then finally Build & Run the application & insert sample input data.It will automatically insert data into InsertData.xml file.

Thank You... Shout it

2 Responses so far.

  1. Anonymous says:

    Thank you!!

    it's good

  2. Anonymous says:


Leave a Reply