An introduction to LINQ to XML
XML stands for Extensible Markup Language. It is a popular markup language that is similar to HTML. It is used for formatting, storing, and transporting data with the help of tags.
LINQ stands for Language Integrated Query. It is a Microsoft .NET Framework technology. It is a set of methods/technologies that provide a consistent way to query data from various resources, such as XML documents and databases. LINQ queries are quite similar to SQL and easy to understand and integrated into .NET languages.
LINQ to XML
LINQ to XML is an extension of LINQ that allows us to manipulate XML documents using LINQ syntax. LINQ to XML works in the following way:
It converts the XML data into LINQ objects.
It manipulates the converted data using LINQ queries.
So, LINQ to XML allows us to load, query, modify and save an XML document using LINQ syntax. To get familiar with the conversion and syntax of LINQ, we'll go through an example.
Loading a document
LINQ to XML allows us to load the XML document. The XDocument.Load method of XDocument class creates a new XDocument instance using an XML file. We specify the path of our sample XML file and then pass it as a parameter to the load function.
string xmlFilePath = "student.xml"; //path to the fileXDocument xmlDoc = XDocument.Load(xmlFilePath);
Querying data
LINQ to XML allows us to use LINQ syntax to query XML data. For querying the data, we'll look into the following method of XElement class:
The
XElement.Descendantsmethod returns the collection of all the descendant elements of an XML element.
var query = from student in xmlDoc.Descendants("student")where (string)student.Attribute("grade") == "1"select new{First_Name = student.Element("first_name").Value,Last_Name = student.Element("last_name").Value,Age = student.Element("age").Value};
Modifying data
With LINQ to XML, we can modify XML data by creating and updating elements, attributes, and values. For this, we'll look into the following methods of XElement.
The
XElement.Addmethod adds an element as a new child.
// Add a new student elementXElement newStudent = new XElement("student",new XElement("first_name", "Kim"),new XElement("last_name", "Joe"),new XElement("grade", "3"));xmlDoc.Element("class").Add(newStudent);
The
XElement.SetValuemethod updates an existing element or attribute.
// Update a student's ageXElement updateAge = student.Age;updateAge.SetValue("4");
Saving data
Like querying and modifying, LINQ to XML provides a simple way to save the data. The XDocument.Save method of XDocument class overwrites the XML file if it exists.
xmlDoc.Save("Student.xml");
You can run the following command to see the updated records in the file student.xml.
cat student.xml
Code example
Press the "Run" button to execute the code:
using System;
using System.Linq;
using System.Xml.Linq;
namespace Example
{
class Program
{
static void Main(string[] args)
{
// Load the XML file
string xmlFilePath = "student.xml";
XDocument xmlDoc = XDocument.Load(xmlFilePath);
// Query the XML using LINQ
var query = from student in xmlDoc.Descendants("student")
where (string)student.Attribute("grade") == "1"
select new
{
First_Name = student.Element("first_name").Value,
Last_Name = student.Element("last_name").Value,
Age = student.Element("age").Value
};
// Print the results
Console.WriteLine("\nPrinting records where grade = 1:");
foreach (var student in query)
{
Console.WriteLine($"\n{student.First_Name} , {student.Last_Name} , {student.Age}");
}
// Add a new student element
XElement newStudent = new XElement("student",
new XElement("first_name", "Kim"),
new XElement("last_name", "Joe"),
new XElement("grade", "3"));
xmlDoc.Element("class").Add(newStudent);
Console.WriteLine("\nNew Student has been added");
// Update a student's age
var update = from student in xmlDoc.Descendants("student")
where (string)student.Attribute("grade") == "2"
select new
{
Age= student.Element("age")
};
foreach (var student in update)
{
XElement updateAge = student.Age;
updateAge.SetValue("4");
}
// save the file
xmlDoc.Save("student.xml");
Console.WriteLine("\nUpdated age where grade = 2");
}
}
}
Code explanation
Lines 12–13: We load our XML file
student.xml.Lines 16–32: We fetch the record where
gradeis equal to1and print all those records to the console.Lines 35–40: We add a new student
newStudentto the file.Lines 43–55: We update the age of the students using the
setValue()method ofXElementwhosegradeis2.Line 57: We save the updated data in our file
student.xml.
Conclusion
LINQ to XML conversion provides us with an easy way to work with XML documents instead of using the traditional complex approach of using DOM.
Free Resources