LINQ to XML in C#: Querying and Building XML

This article provides a comprehensive guide to LINQ to XML in C#, explaining what it is, how it modernizes XML handling in .NET, and how it replaces older XML models. You will learn the core classes of the System.Xml.Linq namespace, how functional construction simplifies XML tree creation, and how LINQ syntax enables clean, type-safe queries without relying on complex XPath strings.

What Is LINQ to XML?

LINQ to XML is an in-memory XML programming API provided in the System.Xml.Linq namespace. Introduced to modernize XML processing in .NET, it leverages the Language Integrated Query (LINQ) framework to provide a more intuitive, efficient, and readable alternative to the traditional W3C-standard Document Object Model (DOM) represented by XmlDocument.

Unlike older APIs, LINQ to XML integrates directly with modern C# language features, such as type inference, lambda expressions, and standard query operators.

Modern XML Tree Construction: Functional Construction

In traditional XmlDocument programming, building an XML tree required creating a document, creating individual element and attribute nodes, and manually appending them to parent nodes in a tedious, imperative sequence.

LINQ to XML introduces functional construction, allowing developers to create an entire XML tree in a single, declarative C# statement using classes like XDocument, XElement, and XAttribute.

Traditional DOM Approach (XmlDocument)

XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Books");
XmlElement book = doc.CreateElement("Book");
book.SetAttribute("id", "1");
XmlElement title = doc.CreateElement("Title");
title.InnerText = "C# in Depth";

book.AppendChild(title);
root.AppendChild(book);
doc.AppendChild(root);

Modern LINQ to XML Approach (XElement)

XDocument doc = new XDocument(
    new XElement("Books",
        new XElement("Book", new XAttribute("id", "1"),
            new XElement("Title", "C# in Depth")
        )
    )
);

Functional construction mirrors the visual hierarchy of XML directly in C# code, significantly reducing boilerplate and improving maintainability.

Modernizing XML Querying

Prior to LINQ to XML, extracting data from XML documents relied heavily on XPath queries via strings (e.g., doc.SelectNodes("//Book[@id='1']")). These strings lacked compile-time type checking and IntelliSense support, making them prone to runtime errors.

LINQ to XML replaces string-based queries with strongly typed LINQ method or query syntax, utilizing axis methods such as Elements(), Descendants(), and Ancestors().

Example: Querying XML Data

XDocument doc = XDocument.Load("library.xml");

// Querying using LINQ method syntax
var programmingBooks = doc.Descendants("Book")
    .Where(b => (string)b.Element("Category") == "Programming")
    .Select(b => new
    {
        Id = (int)b.Attribute("id"),
        Title = (string)b.Element("Title"),
        Price = (decimal)b.Element("Price")
    });

foreach (var book in programmingBooks)
{
    Console.WriteLine($"{book.Title} - ${book.Price}");
}

LINQ to XML automatically handles type conversion via explicit casting operators on XElement and XAttribute objects, eliminating the need for manual string parsing (e.g., int.Parse()).

Key Advantages Over Traditional APIs