Saturday, 12 September 2009

Testing XML

Hello Friends........

In this post, we are going to learn how to use XML for storing and transferring the data.Here we will not use any database for data, instead we will use xml file for storing and retrieving our data.First of all lets create our XML file.

Add a new xml file in your project and add following data to your XML file :


< Profile>
< record>
< Name>Kartik Shrivastava< /Name>
< Designation>Software Developer< /Designation>
< Experience>3 yrs< /Experience>
< Company>Wpf Inc< /Company>
< /record>
< record>
< Name>Adam Mills< /Name>
< Designation>Graphics Designer< /Designation>
< Experience>4 yrs< /Experience>
< Company>Windser Ltd< /Company>
< /record>
< /Profile>


Here we have created an XML file with two records.Here the column names are Name,Designation,Experience and Company.Now create a web for that will consist of a gridview control for showing the data retrieved from XML file and four text boxes for inserting new record in to our XML file in following manner :


Now create a method named BindGrid(), that will fetch the data from the XML file and will bind it to our gridview control.

public void BindGrid()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("DataFile.xml"));
GridView1.DataSource = ds;
GridView1.DataBind();
}


And call this BindGrid() method on pageload event :

BindGrid();

Now run your application.Your application will look like this :

Now we create another method Addrecord() for inserting new records into our XML file in following manner :

public DataSet AddRecord()
{
DataSet ds = new DataSet();
ds.ReadXml(Server.MapPath("DataFile.xml"));

DataRow dr = ds.Tables[0].NewRow();
dr["Name"] = TextBox1.Text;
dr["Designation"] = TextBox2.Text;
dr["Experience"] = TextBox3.Text;
dr["Company"] = TextBox4.Text;
ds.Tables[0].Rows.Add(dr);

return ds;
}


Now we call this AddRecord() method on the click event of our Add Record button in the following manner :

DataSet ds = new DataSet();
ds = AddRecord();
ds.WriteXml(Server.MapPath("DataFile.xml"));
BindGrid();

Now again run your application and insert new record into text boxes :

Now when you click the Add Record button, the new record gets inserted into our XML file that you can see in our gridview :

So here we are done now.Now use Some more logic and try to use XML in your own way.Store data in xml files and transport it to your application in your own way.
Good Luck And Have Fun........

Download Full Source Code Here [C#/VB.Net]

Testing XML
Testing XML.rar
Hosted by eSnips

No comments: