C#: LINQ to XML

Updated on September 21, 2015 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.

An XML DOM.

A set of about 10 supplementary query operators.

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.