CRUD operations using LINQ to XML

by Jagadish Pulakhandam on 2/3/2012 10:19:05 AM
Rated 4.5 from 2 votes
Brief: Demonstrates on loading XML file, adding, updating, deleting nodes etc. using LINQ to XML in .NET
Posted to: LINQ to XML
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Demonstrates the following:
  • using LINQ to XML classes in .NET
  • Loading an XML file (or document) using XDocument class
  • Searching for single/multiple nodes in an XDocument (using XPath)
  • Extracting data/values in nodes (using XElement)
  • Retrieving Child Nodes (and values using XElement)
  • Retrieving Attributes of nodes (and values using XElement)
  • Adding Nodes (at a particular location in an XML Document or to child nodes using XElement)
  • Updating Node data/information (using XElement)
  • Deleting specific Nodes (using XElement)
  • Moving Nodes from one place to another in an XML document (using XElement)
  • Working with Attributes

Screen shot:



Source code:

Sample XML used:

<?xml version="1.0" encoding="utf-8"?>
<CompanyInfo>
  <DepartmentInfo>
    <!-- contains all departments and employees-->
    <Department ID="D10">
      <Deptno>10</Deptno>
      <Dname>Accounting</Dname>
      <Location>Dallas</Location>
      <EmployeeInfo>
        <Employee ID="E1">
          <Empno>1001</Empno>
          <Ename>Jag</Ename>
          <Sal>2300</Sal>
          <Deptno>10</Deptno>
        </Employee>
        <Employee ID="E2">
          <Empno>1002</Empno>
          <Ename>Chat</Ename>
          <Sal>3400</Sal>
          <Deptno>10</Deptno>
        </Employee>
        <Employee ID="E3">
          <Empno>1003</Empno>
          <Ename>Winner</Ename>
          <Sal>4500</Sal>
          <Deptno>10</Deptno>
        </Employee>
      </EmployeeInfo>
    </Department>
    <Department ID="D20">
      <Deptno>20</Deptno>
      <Dname>Sales</Dname>
      <Location>New York</Location>
      <EmployeeInfo>
        <Employee ID="E4">
          <Empno>1004</Empno>
          <Ename>Ram</Ename>
          <Sal>3400</Sal>
          <Deptno>20</Deptno>
        </Employee>
        <Employee ID="E5">
          <Empno>1005</Empno>
          <Ename>Raj</Ename>
          <Sal>4500</Sal>
          <Deptno>20</Deptno>
        </Employee>
      </EmployeeInfo>
    </Department>
    <Department ID="D30">
      <Deptno>30</Deptno>
      <Dname>Production</Dname>
      <Location>DC</Location>
      <EmployeeInfo>
        <Employee ID="E6">
          <Empno>1006</Empno>
          <Ename>aaa</Ename>
          <Sal>3400</Sal>
          <Deptno>30</Deptno>
        </Employee>
        <Employee ID="E7">
          <Empno>1007</Empno>
          <Ename>bbb</Ename>
          <Sal>4300</Sal>
          <Deptno>30</Deptno>
        </Employee>
      </EmployeeInfo>
    </Department>
    <Department ID="D40">
      <Deptno>40</Deptno>
      <Dname>IT</Dname>
      <Location>LA</Location>
      <EmployeeInfo>
        <Employee ID="E8">
          <Empno>1008</Empno>
          <Ename>xxx</Ename>
          <Sal>2900</Sal>
          <Deptno>40</Deptno>
        </Employee>
        <Employee ID="E9">
          <Empno>1009</Empno>
          <Ename>yyy</Ename>
          <Sal>4600</Sal>
          <Deptno>40</Deptno>
        </Employee>
      </EmployeeInfo>
    </Department>
  </DepartmentInfo>
</CompanyInfo>

Source Code:

001.using System;
002.using System.Linq;
003.using System.Windows.Forms;
004.using System.Xml.Linq;
005. 
006.namespace LinqToXmlDemo
007.{
008.    public partial class Form1 : Form
009.    {
010. 
011.        const string XMLDOCFILEPATH = "..\\..\\MyData.xml";
012.        XDocument doc;
013. 
014.        public Form1()
015.        {
016.            InitializeComponent();
017.        }
018. 
019.        private void Form1_Load(object sender, EventArgs e)
020.        {
021.            RefreshXDoc();
022.        }
023. 
024.        private void RefreshXDoc()
025.        {
026.            doc = XDocument.Load(XMLDOCFILEPATH);
027.            btnRefresh_Click(null, null);
028.        }
029. 
030.        private void SaveXDoc()
031.        {
032.            doc.Save(XMLDOCFILEPATH);
033.            RefreshXDoc();
034.            btnClear_Click(null, null);
035.        }
036. 
037.        private void btnRefresh_Click(object sender, EventArgs e)
038.        {
039.            var q = doc.Descendants().Elements("Employee").Select(emp => new
040.            {
041.                ID = emp.Attribute("ID").Value,
042.                Empno = emp.Element("Empno").Value,
043.                Ename = emp.Element("Ename").Value,
044.                Sal = emp.Element("Sal").Value,
045.                Deptno = emp.Element("Deptno").Value
046.            });
047. 
048.            this.DataGridView1.DataSource = q.ToList();
049. 
050.        }
051. 
052.        private void btnClear_Click(object sender, EventArgs e)
053.        {
054.            foreach (Control c in this.Controls)
055.            {
056.                if (c is TextBox)
057.                {
058.                    ((TextBox)c).Text = string.Empty;
059.                }
060.            }
061.        }
062. 
063.        private void btnSearch_Click(object sender, EventArgs e)
064.        {
065.            var o = doc.Descendants().Elements("Employee")
066.                .Where(emp => emp.Element("Empno").Value == this.txtEmpno.Text)
067.                .Select(emp => new
068.                {
069.                    ID = emp.Attribute("ID").Value,
070.                    Empno = emp.Element("Empno").Value,
071.                    Ename = emp.Element("Ename").Value,
072.                    Sal = emp.Element("Sal").Value,
073.                    Deptno = emp.Element("Deptno").Value
074.                })
075.                .FirstOrDefault();
076. 
077.            if (o == null)
078.            {
079.                MessageBox.Show("Not found");
080.                return;
081.            }
082. 
083.            txtEname.Text = o.Ename;
084.            txtSal.Text = o.Sal;
085.            txtDeptno.Text = o.Deptno;
086.            txtID.Text = o.ID;
087.        }
088. 
089.        private void btnAdd_Click(object sender, EventArgs e)
090.        {
091.            var oDept = doc.Descendants().Elements("Department")
092.                .Where(d => d.Element("Deptno").Value == this.txtDeptno.Text)
093.                .FirstOrDefault();
094. 
095.            if (oDept == null)
096.            {
097.                MessageBox.Show("Department/EmployeeInfo not found");
098.                return;
099.            }
100. 
101.            XElement oEmp = new XElement("Employee");
102.            oEmp.Add(new XAttribute("ID", txtID.Text));
103.            oEmp.Add(new XElement("Empno", txtEmpno.Text));
104.            oEmp.Add(new XElement("Ename", txtEname.Text));
105.            oEmp.Add(new XElement("Sal", txtSal.Text));
106.            oEmp.Add(new XElement("Deptno", txtDeptno.Text));
107. 
108.            oDept.Element("EmployeeInfo").Add(oEmp);
109.            SaveXDoc();
110. 
111.            MessageBox.Show("Added Succefully!");
112. 
113.        }
114. 
115.        private void btnUpdate_Click(object sender, EventArgs e)
116.        {
117.            var oEmp = doc.Descendants().Elements("Employee")
118.                .Where(d => d.Element("Empno").Value == this.txtEmpno.Text)
119.                .FirstOrDefault();
120. 
121.            if (oEmp == null)
122.            {
123.                MessageBox.Show("Not found");
124.                return;
125.            }
126. 
127.            if (oEmp.Element("Deptno").Value.Equals(txtDeptno.Text))
128.            {
129.                //The following would simply modify and update the record
130.                //However, it would not detach and attach to another dept branch (if dept is different, else would execute)
131.                oEmp.Element("Ename").Value = txtEname.Text;
132.                oEmp.Element("Sal").Value = txtSal.Text;
133.                oEmp.Attribute("ID").Value = txtID.Text;
134.            }
135.            else
136.            {
137.                //go to the Department node of provided department
138.                var oDept = doc.Descendants().Elements("Department")
139.                    .Where(d => d.Element("Deptno").Value == this.txtDeptno.Text)
140.                    .FirstOrDefault();
141. 
142.                if (oDept == null)
143.                {
144.                    MessageBox.Show("Department/EmployeeInfo not found");
145.                    return;
146.                }
147. 
148.                //remove node from current location
149.                oEmp.Remove();
150.                //addding node to new location
151.                XElement oEmp2 = new XElement("Employee");
152.                oEmp2.Add(new XAttribute("ID", txtID.Text));
153.                oEmp2.Add(new XElement("Empno", txtEmpno.Text));
154.                oEmp2.Add(new XElement("Ename", txtEname.Text));
155.                oEmp2.Add(new XElement("Sal", txtSal.Text));
156.                oEmp2.Add(new XElement("Deptno", txtDeptno.Text));
157. 
158.                oDept.Element("EmployeeInfo").Add(oEmp2);
159.            }
160. 
161.            SaveXDoc();
162.            MessageBox.Show("Updated Succesfully!");
163.        }
164. 
165.        private void btnDelete_Click(object sender, EventArgs e)
166.        {
167.            var oEmp = doc.Descendants().Elements("Employee")
168.                .Where(d => d.Element("Empno").Value == this.txtEmpno.Text)
169.                .FirstOrDefault();
170. 
171.            if (oEmp == null)
172.            {
173.                MessageBox.Show("Not found");
174.                return;
175.            }
176. 
177.            oEmp.Remove();
178.            SaveXDoc();
179.            MessageBox.Show("Deleted Succesfully!");
180.        }
181. 
182. 
183.    }
184.}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 4.5 from 2 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following