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 🙂
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.
Leon Kennedy says
Do you have an example of how to do this in a web application (asp.net form)?