Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Basics of LINQ To XML

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 174
    Comment on it

    Getting Started With LINQ To XML:

        Before starting with LINQ To XML,I am assuming that we all are familiar with the LINQ basics, incase if someone has no idea about it, he can visit the following url of my previous blog about LINQ basics:

    http://findnerd.com/list/view/LINQ-Basics/3232/

    Also you can have a look to 'LINQ To SQL' for your knowledge at:

    http://findnerd.com/list/view/Basics-of-LINQ-To-SQL/3246/

      In this blog we will discuss about retrieving, inserting, deleting and modify existing data to and from xml file using LINQ.

      Let us consider the following basic XML structure to better understand the operations performed over it:

    <?xml version="1.0" encoding="utf-8" ?>
    <Students>
      <Student ID="1">
        <Name>Rohan</Name>   
      </Student>
      <Student ID="2">
        <Name>Sohan</Name>   
      </Student>
      <Student ID="3">
        <Name>Mohan</Name>   
      </Student> 
    </Students>
    

      In the above example there is a root element named students which contains a set of elements with student tag and each student has an attribute id and an inner element name.

    Retrieving Data Using linq To XML:

      Let us understand with the help of the following example-

    private string path = "Testing.xml";
    
            private void GetXMLData()
            {
                try
                {
                    XDocument testXML = XDocument.Load(path);
                    var students = from student in testXML.Descendants("Student")
                                    select new
                                    {
                                        ID = Convert.ToInt32(student.Attribute("ID").Value),
                                        Name = student.Element("Name").Value
                                    };
    
                    foreach (var student in students)
                    {
                       // Do other operations with each student object
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
    

      For retrieving data we first need to create an XDocument object of the XML file. Now as we get a valid XDocument object we can apply LINQ to it (We use "xDocObject.Descendants (elementTagName)" inorder to specify the element to be queried).Now as we get all the records we can easily iterate it with the help of foreach loop.

    Data Insertion using Linq To XML:

      For insertion we first need to create an XElement object that will be inserted (make sure that the XElement is completely synchronized with the xml files format).We will then add it to the Xdocument objects and finally overwrite the existing xml file.

    Example:

    private void InsertXMLData(string name)
            {
                try
                {
                    XDocument testXML = XDocument.Load(path);              
    
                    XElement newStudent = new XElement("Student",                                 
    
    
                                                   new XElement("Name", name)                     
    
    
                                               );
    
                    newStudent.SetAttributeValue("ID",4);              
                    testXML.Element("Students").Add(newStudent);
                    testXML.Save(path);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
    

      In the above example we created an XDocument object of the xml file then we created a XElement object exactly same as the xml file's format then by assigning the ID attribute to the XElement object it is added to the XDocument object and the xml file is saved.

    Data Modification using Linq To XML:

      For data modification first we have to select the record to be modified based on some parameter, then we keep the retrieved data into the XElement object and make the changes and then finaly save it in the XDocument object.

    private void UpdateXMLData(string name,int id)
            {
                try
                {
                    XDocument testXML = XDocument.Load(path);
                    XElement cStudent = testXML.Descendants("Student").Where(c => c.Attribute
    
    ("ID").Value.Equals(id.ToString())).FirstOrDefault();
    
                    cStudent.Element("Name").Value = name;
                    testXML.Save(path);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
    

      In the above example we created an XDocument object of the xml file then we selected the record to be modified based on the id parameter supplied, then while keeping the retrieved data into the XElement object we made the changes in the name and finaly saved the file.

    Data Deletion using Linq To XML:

      For data deletion first we have to select the record to be deleted based on some parameter then we call remove method on XElement object this makes some elimination on the XDocument object and finaly save the xml file.

    private void DeleteXMLData(int id)
           {
               try
               {
                   XDocument testXML = XDocument.Load(path);
                   XElement cStudent = testXML.Descendants("Student").Where(c => c.Attribute
    
    ("ID").Value.Equals(id.ToString())).FirstOrDefault();
                   cStudent.Remove();
                   testXML.Save(path);
               }
               catch (Exception err)
               {
                   MessageBox.Show(err.Message);
               }
           }
    

      In the above example we created an XDocument object of the xml file then we selected the record to be deleted based on the id parameter supplied, then while keeping the retrieved data into the XElement object we call remove method which makes the elimination in the XDocument and finaly save the changes in the xml file.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: