Updated on Kisan Patel
The .Net Framework provides a number of APIs for working with XML data. LINQ to XML is the API for processing the XML document.
LINQ to XML provides an extensive collection of classes for a variety of purposes. These classes reside in the System.Xml.Linq
namespace from the System.Xml.Linq.dll
assembly. Here, some of the most commonly used classes from this hierarchy.
The XNode abstract class represents a node of an XML tree. The XContainer, XText, XComment, and XProcessingInstruction classes inherit from the XNode class. The XContainer class in turn acts as a base class for the XDocument and XElement classes. As you might have guessed, these classes represent a text node, comment, processing instruction, XML document, and element, respectively.
The classes such as XAttribute, XComment, XCData, and XDeclaration are independent of the XNode hierarchy and represent attribute, comment, CDATA section, and XML declaration, respectively. The XName class represents the name of an element (XElement) or attribute (XAttribute). Similarly, the XNamespace class represents a namespace of an element or attribute.
LINQ to XML comprises two things.
Now, let’s move on to take a look at a LINQ to XML example and find student names from an XML file. LINQ to XML loads an XML document into a query-able XElement type and then IEnumerable loads the query results, and using a foreach loop, we access it.
students.xml
<?xml version="1.0" encoding="utf-8" ?> <students> <student id="1"> <name>Kisan</name> <city>Ladol</city> </student> <student id="2"> <name>Ravi</name> <city>Vijapur</city> </student> <student id="3"> <name>Ujas</name> <city>Ladol</city> </student> <student id="4"> <name>Ketul</name> <city>Ladol</city> </student> </students>
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace ConsoleApp { class Program { static void Main(string[] args) { //Load XML File XElement xmlFile = XElement.Load(@"c:\students.xml"); //Query Creation IEnumerable students = from s in xmlFile.Elements("student").Elements("name") select s; //Execute Query foreach (string student in students) { Console.WriteLine(student); } } } }
Above program produce following output.
As Seen in above example, LINQ to XML offers a slightly different syntax that operates on XML data, allowing query and data manipulation.