How to insert data in XML file using LINQ to XML?


Step1:Create one class i.e Emp.cs and declare the property like this

public class Emp
{
public int Id { get; set; }
public string EmpName { get; set; }
public string EmpSal { get; set; }
}

Step2: Create the Emp.xml file like this in Solution Explore

<?xml version="1.0" encoding="utf-8"?>
<Emps>

</Emps>

Step3: Write the code in code behind like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

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

}
protected void Button1_Click(object sender, EventArgs e)
{
XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("Emp.xml"));

XElement newEmp = new XElement("Emp",
new XElement("EmpName", TextBox1.Text),
new XElement("EmpSal", TextBox2.Text)
);
newEmp.SetAttributeValue("Id", GetNextAvailableID());

data.Element("Emps").Add(newEmp);
data.Save(HttpContext.Current.Server.MapPath("Emp.xml"));

TextBox1.Text = "";
TextBox2.Text = "";

FillGrid();

}

private static int GetNextAvailableID()
{
XDocument data = XDocument.Load(HttpContext.Current.Server.MapPath("Emp.xml"));

return Convert.ToInt32(
(from c in data.Descendants("Emp")
orderby Convert.ToInt32(c.Attribute("Id").Value) descending
select c.Attribute("Id").Value).FirstOrDefault()
) + 1;
}

protected void FillGrid()
{
var query = from a in XElement.Load(MapPath("Emp.xml")).Elements("Emp")
select new Emp
{

Id = Convert.ToInt32(a.Attribute("Id").Value),
EmpName = (string)a.Element("EmpName"),
EmpSal = (string)a.Element("EmpSal")

};

GridView1.DataSource = query;
GridView1.DataBind();
}
}

Advertisements
Posted in LINQ, XML. 2 Comments »

2 Responses to “How to insert data in XML file using LINQ to XML?”

  1. Niranjan kumar Says:

    After use this code followin Error Occured :

    Error 1 The type or namespace name ‘Emp’ could not be found (are you missing a using directive or an assembly reference?) D:\MProjectXML\ClientList.aspx.cs 104 32 D:\MProjectXML\

  2. Chandra Dev Says:

    Hi

    Please add one class in Solution Exp i.e Emp.cs and declare the property like this
    public class Emp
    {
    public int Id { get; set; }
    public string EmpName { get; set; }
    public string EmpSal { get; set; }
    }

    I have updated the article. Please check it. If you want source code then let me inform.

    Regards
    chandradev


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: