In my earlier articles, I described working with Linq on an SQL server database, which is 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 modifying existing data to and from XML files 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>
Code language: HTML, XML (xml)
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);
}
}
Code language: PHP (php)
At first, we will need to create an “XDocument” object from the XML file. Simply passing the file location as a parameter of the 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 a 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 an object of that class. In the 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 into an XML file using Linq is pretty straightforward. First, we will need to prepare a proper XElement object to be inserted. Here again, we need to be careful that the constructed XElement is completely synchronized with the XML file’s format. 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);
}
}
Code language: PHP (php)
Modify Existing Data Using Linq To XML:
To change the 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 to the XDocument object class. Notice that we don’t need to reassign the modified XElement object as it is 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);
}
}
Code language: JavaScript (javascript)
Delete A Record From XML File Using Linq:
To delete a record, we simply need to retrieve it and then call the “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);
}
}
Code language: JavaScript (javascript)
Reference:
I hope this link to the XML tutorial will help you to some extent. Surely, you will need to study many more to work more deeply in this area. MSDN has very easy, understandable documentation on linq to XML, which should be of great help. Happy coding 🙂
Leon Kennedy says
Do you have an example of how to do this in a web application (asp.net form)?