hello........
Iam facing problem in XML....
I want to save employee records in XML file using user input....
But when i tried to save the data in XML File ...it is storing only one record ...
try to solve my problem so that i can add multiple records in the XML file..........
by one record i mean that..
i want to save employee details like employee no,employee name, salary and job....
when i tried to save the data.. it saves the record of only one employee...and it replaces the previous saved record ihv used following code to save the data
public void SaveData()
{
dtbl = new DataTable("emp");
dtbl.Columns.Add(new DataColumn("EmpNo",Type.GetType("System.String")));
dtbl.Columns.Add(new DataColumn("EmpName", Type.GetType("System.String")));
dtbl.Columns.Add(new DataColumn("EmpJob", Type.GetType("System.String")));
dtbl.Columns.Add(new DataColumn("EmpSalary", Type.GetType("System.String")));
//DataTable dt = display_data();
if (dtbl.Rows.Count > 0)
{
DataRow r = dtbl.NewRow();
r[0] = txtEmployeeNumber.Text;
r[1] = txtEmployeeName.Text;
r[2] = txtJob.Text;
r[3] = txtSalary.Text;
dtbl.Rows.Add(r);
str = Server.MapPath("XMLEmp.xml");
dtbl.WriteXml(str);
dtbl.AcceptChanges();
lblMsg.Text = "Data Saved";
}
SaveData() is the function which i hv called in btnSave_click
and str is varible of string datatype
now you can solve my problem easily...
Thanks.............
Loading
Satyapriya NayakPosted Jun 8, 2010, 1:25 AM
Here is a solution for your problem.
Code:-
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.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
static DataSet ds;
static DataTable dt;
static DataRow dr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ds = new DataSet();
ds.ReadXml(MapPath("data.xml"));
dt = ds.Tables["student"];
}
}
protected void btnaddrecords_Click(object sender, EventArgs e)
{
dr = dt.NewRow();
dr["sid"] = TextBox1.Text;
dr["sname"] = TextBox2.Text;
dr["smarks"] = TextBox3.Text;
dr["saddress"] = TextBox4.Text;
dt.Rows.Add(dr);
ds.WriteXml(Server.MapPath("data.xml"));
Response.Write("Record Successfully Inserted");
clear();
}
void clear()
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
}
}
Design:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
http://www.w3.org/1999/xhtml">
Data.xml:- Here you have to insert only one record in the root element otherwise it will give an error,then you can insert as many records you want.
Plz run the attachment.....
Thanks
If this helps you plz mark it as (Accepted Answer)