Thursday, January 20, 2011

LINQ - Insert,Update,Delete data in XML by using Linq to XML

In this article i will show you how to insert,update and delete data in xml by using LINQ to XML.

Step 1
Create a Console application and give the solution name as LinqToXML_IUD.

Step 2
In console application base directory(debug folder) insert XML file and give the file name as Customers.xml.

Step 3
The XML in the following example defines an XML document with a root node called Customers. This root node contains one or more nodes called Customer that include elements called ID,FirstName,LastName and Location.


<?xml version="1.0" encoding="utf-8"?>
<Customers>
  <Customer>
    <ID>1</ID>
    <FirstName>kishor</FirstName>
    <LastName>Naik</LastName>
    <Location>Mumbai</Location>
  </Customer>
</Customers>

Step 4
Create a Customer class in the solution,it is an entity class,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToXML_IUD
{
    public class Customer
    {
        #region Property

        public int ID
        {
            get;
            set;
        }

        public String FirstName
        {
            get;
            set;
        }

        public String LastName
        {
            get;
            set;
        }

        public String Location
        {
            get;
            set;
        }

        #endregion
    }
}

Step 5
Create a CustomerDAL static class in a solution for insert,update and delete data to XML document,it is look like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToXML_IUD
{
    public static class CustomerDAL
    {
        #region Methods

        /// <summary>
        /// Insert Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Insert(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                // Load Xml Document
                System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                // Add the elements
                System.Xml.Linq.XElement XNew = new System.Xml.Linq.XElement("Customer",
                                                                new System.Xml.Linq.XElement("ID", CustomerObj.ID),
                                                                new System.Xml.Linq.XElement("FirstName", CustomerObj.FirstName),
                                                                new System.Xml.Linq.XElement("LastName", CustomerObj.LastName),
                                                                new System.Xml.Linq.XElement("Location", CustomerObj.Location)  
                                                                );

                XDoc.Add(XNew); 

                // Save the Xml File
                XDoc.Save(XmlFile);

                Flag = true; 
 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        /// <summary>
        /// Update Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Update(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                // Load Xml Document
                System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                // Obtain single customer data from XML file by passing CustomerID
                IEnumerable<System.Xml.Linq.XElement> Query = from Q in XDoc.Elements("Customer")
                                                              where Q.Element("ID").Value == Convert.ToString(CustomerObj.ID)
                                                              select Q; 
                                                      
                // Check the count is grether thae equal 1
                if (Query.Count() >= 1)
                {
                    // Replace the element
                    foreach (System.Xml.Linq.XElement X in Query)
                    {
                        X.SetElementValue("FirstName", CustomerObj.FirstName);
                        X.SetElementValue("LastName", CustomerObj.LastName);
                        X.SetElementValue("Location", CustomerObj.Location); 
   
                    }

                    // Save the Xml File
                    XDoc.Save(XmlFile);
                    Flag = true;  
                }

                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        /// <summary>
        /// Delete Customers Data in a XML file.
        /// </summary>
        /// <param name="CustomerObj">Specify the Customer Object</param>
        /// <returns>Boolean</returns>
        public static Boolean Delete(Customer CustomerObj)
        {
            Boolean Flag = false; 
            try
            {
                // XML document Full File Path
                 String XmlFile=AppDomain.CurrentDomain.BaseDirectory+"Customers.xml";

                 // Load Xml Document
                 System.Xml.Linq.XElement XDoc = System.Xml.Linq.XElement.Load(XmlFile);

                 // Obtain single customer data from XML file by passing CustomerID
                 IEnumerable<System.Xml.Linq.XElement> Query = (from Q in XDoc.Elements("Customer")
                                                  where Q.Element("ID").Value == Convert.ToString(CustomerObj.ID)
                                                  select Q);

                 // Check the count is grether thae equal 1
                 if (Query.Count() >= 1)
                 {
                     // Remove the element
                     foreach (System.Xml.Linq.XElement X in Query)
                     {
                         X.Remove(); 
                     }

                     // Save the Xml File
                     XDoc.Save(XmlFile);
                     Flag = true; 
                 }

                 
                
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);  
            }

            return Flag; 
        }

        #endregion
    }
}

Step 6
Call a methods in Main function,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToXML_IUD
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                #region Insert Section
                // Create a Object of Customer class
                Customer CustomerInsertObj = new Customer();

                // Add data in object
                CustomerInsertObj.ID = 6;
                CustomerInsertObj.FirstName = "Kakashi";
                CustomerInsertObj.LastName = "Hatake";
                CustomerInsertObj.Location = "Osaka";

                // Call Insert function
                if (CustomerDAL.Insert(CustomerInsertObj))
                {
                    System.Console.WriteLine("Insert Sucessfully");
                }


                #endregion


                //#region Update Section
                //// Create a Object of Customer class
                //Customer CustomerUpdateObj = new Customer();

                ////Add data in object
                //CustomerUpdateObj.ID = 6;
                //CustomerUpdateObj.FirstName = "Naruto";
                //CustomerUpdateObj.LastName = "OzoMaki";
                //CustomerUpdateObj.Location = "Osaka";

                //// Call Update function
                //if(CustomerDAL.Update(CustomerUpdateObj))
                //{
                //    System.Console.WriteLine("Update Sucessfully");   
                //}

                //#endregion


                //#region Delete Section
                //// Create a Object of Customer class
                //Customer CustomerDeleteObj = new Customer();

                ////Add data in object
                //CustomerDeleteObj.ID = 6;

                //// Call Delete function
                //if (CustomerDAL.Delete(CustomerDeleteObj))
                //{
                //    System.Console.WriteLine("Delete Sucessfully");   
                //}
                //#endregion

            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);   
            }
        }
    }
}

Run the project.

Download
Download Source Code

2 comments: