• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Apply LinQ To XML Data Using C#

Apply LinQ To XML Data Using C#

October 4, 2011 by Rana Ahsan 1 Comment

linq to xml tutorial

On my earlier articles, I have described about working with linq on sql server database, which usually known as ‘Linq To SQL‘. Today I am going to show how linq can be applied on XML data along with c# code examples. This is known as ‘Linq To XML’.I am assuming you are already familiar with basic Linq usage. If not, my suggestion will be to study the basics of Linq first. Here, in this tutorial, i will show the most basic operations such as retrieving data(select), inserting data,deleting data and modify existing data to and from xml file using linq.

Sample Data:

For this simple exercise, we will be using a very basic xml file structure as follows:

<?xml version="1.0" encoding="utf-8" ?>
<Students>
  <Student ID="1">
    <Name>Test1</Name>    
  </Student>
  <Student ID="2">
    <Name>Test2</Name>    
  </Student>
  <Student ID="3">
    <Name>Test3 </Name>    
  </Student>  
</Students>

This file has a root element named ‘students’ which contains a set of elements with ‘student’ tag, refers to each student in the data set. Each ‘student’ has an attribute ‘id’ and an inner element ‘name’. For more complex structure we can add as many attributes/inner elements we want.

Retrieving Data Using linq To XML:

At first I am going to put a code snippet that will actually do that work of retrieving data from xml file. Then I will explain how its working on each step.

private string path = "TestData.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);
            }
        }

At first, we will need to create and “XDocument” object from the xml file. Simply passing the file location as parameter of constructor will do fine. Here, two things need to be remembered carefully:

  • If the xml file is not in valid xml format, then it will throw an exception.
  • The example given above is for desktop app format, where it requires that the xml file is in the current directory from where the application is running. If you need to specify some other location, you must need to be specify the absolute URI for that file. If it’s an web application, then you will may need to use Server.MapPath() method to specify the uri correctly.

Now as soon as we get a valid XDocument object, we are ready to apply the linq operation on it. To specify the elements to be queried, we need to use “xDocObject.Descendants(elementTagName)” pattern. You can see we have used similar expression on the linq query. While selecting, you can either create a dynamic object with the properties you need. Or you can declare in advance, a class with members and create object of that class. On above code, we have used the simplified dynamic object approach.


Read All LinQ Tutorials By CodeSamplez.com

Inserting Data Using Linq To XML:

Inserting data to xml file using linq is pretty straight forward. first we will need to prepare a proper XElement object that will be inserted. Here again, need to be careful that, the constructed XElement is completely synchronized with the xml file’s format. And then, we need to add it to the ‘Xdocument’ objects corresponding element collection and finally overwrite the existing xml file. Here is the code example for this:

private void InsertXMLData(string name)
        {
            try
            {
                XDocument testXML = XDocument.Load(path);               
                
                XElement newStudent = new XElement("Student",                                               
                                               new XElement("Name", name)                                               
                                           );
                var lastStudent = testXML.Descendants("Student").Last();

                int newID =  Convert.ToInt32(lastStudent.Attribute("ID").Value);
                newStudent.SetAttributeValue("ID",4);               
                testXML.Element("Students").Add(newStudent);
                testXML.Save(path);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

Modify Existing Data Using Linq To XML:

To change existing record in the xml file, first we will need to retrieve the record matched against some constraints, like matching the id attribute or matching the name value. Keep the retrieved data in XElement, then make the necessary changes and finally apply the save operation on the XDocument object class. Notice that, we don’t need to reassign the modified XElement object as its being referenced internally from the XDocument object and apply the necessary changes while saving. Following is the code sample to do the modification:

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);
            }
        }

Delete A Record From XML File Using Linq:

To delete a record, simply we need to retrieve it and then call “Remove” method of this XElement Object. which will make the necessary elimination in the XDocument object and finally will apply the changes while overwriting the xml file. Following is the code example that will delete a record:

 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);
            }
        }

Reference:

Hope this linq to xml tutorial will help you in some extent. Surely, you will need to study about many more for working more deeply in this area. MSDN has a very easy understandable documentation on linq to xml, which should be of great help. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: .net, c#, linq

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. Leon Kennedy says

    February 10, 2018 at 5:03 pm

    Do you have an example of how to do this in a web application (asp.net form)?

    Reply

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery
  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • How To Work With Codeigniter Caching In PHP
    How To Work With Codeigniter Caching In PHP
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Popular Tutorials

  • How To Work With C# Serial Port Communication
  • PHP HTML5 Video Streaming Tutorial
  • Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
  • Control HTML5 Audio With Jquery
  • How To Work With JSON In Node.js / JavaScript
  • How To Work With Codeigniter Caching In PHP
  • Get Facebook C# Api Access Token
  • Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#

Recent Tutorials

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023