Showing posts with label xml read write. Show all posts
Showing posts with label xml read write. Show all posts

17 August 2011

xml read, write, modify data in asp.net

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

public partial class wsex : System.Web.UI.Page
{
string xmlfile = @"C:\vision\first\emp.xml";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
getdata();
}
void getdata()
{
wsxml ws = new wsxml();
GridView1.DataSource = ws.getdata();
GridView1.DataBind();
}

protected void Button1_Click(object sender, EventArgs e)//insert
{
XmlDocument xd = new XmlDocument();
xd.Load(xmlfile);
XmlElement xe = xd.CreateElement("emp");

XmlElement id = xd.CreateElement("id");
id.InnerText = TextBox1.Text;
xe.AppendChild(id);

XmlElement nam = xd.CreateElement("name");
nam.InnerText = TextBox2.Text;
xe.AppendChild(nam);

XmlElement ad = xd.CreateElement("add");
ad.InnerText = TextBox3.Text;
xe.AppendChild(ad);

xd.DocumentElement.AppendChild(xe);
xd.Save(xmlfile);
Response.Redirect("~/wsex.aspx");

}
protected void Button2_Click(object sender, EventArgs e)//update
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("emp.xml"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (TextBox1.Text == ds.Tables[0].Rows[i]["id"].ToString())
{
ds.Tables[0].Rows[i]["name"] = TextBox2.Text;
ds.Tables[0].Rows[i]["add"] = TextBox3.Text;
ds.WriteXml(Server.MapPath("emp.xml"));
}
}
Response.Redirect("~/wsex.aspx");
}
protected void Button3_Click(object sender, EventArgs e)//delete
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("emp.xml"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (TextBox1.Text == ds.Tables[0].Rows[i]["id"].ToString())
{
ds.Tables[0].Rows[i].Delete();
ds.WriteXml(Server.MapPath("emp.xml"));
}
}
Response.Redirect("~/wsex.aspx");
}
}
emp.xml:


<?xml version="1.0" standalone="yes"?>

<employee>

  <emp>

    <id>1</id>

    <name>s</name>

    <add>s</add>

  </emp>

  <emp>

    <id>2</id>

    <name>b</name>

    <add>che</add>

  </emp>

  <emp>

    <id>3</id>

    <name>c</name>

    <add>ban</add>

  </emp>

</employee>




wsxml:(webservice class)



[WebMethod]

    public DataSet getdata()

    {

        DataSet ds = new DataSet();

        ds.ReadXml(Server.MapPath("emp.xml"));

        return ds;

    }