Chapter 10. LINQ to XML
.NET provides a number of APIs for working with XML data. The primary choice for general-purpose XML document processing is LINQ to XML. LINQ to XML comprises a lightweight, LINQ-friendly XML document object model, plus a set of supplementary query operators.
In this chapter, we concentrate entirely on LINQ to XML. In Chapter 11, we cover the forward-only XML reader/writer, and in the online supplement, we cover the types for working with schemas and stylesheets. .NET also includes the legacy XmlDocument
-based DOM, which we don’t cover.
Note
The LINQ to XML Document Object Model (DOM) is extremely well designed and highly performant. Even without LINQ, the LINQ to XML DOM is valuable as a lightweight façade over the low-level XmlReader
and XmlWriter
classes.
All LINQ to XML types are defined in the System.Xml.Linq
namespace.
Architectural Overview
This section starts with a very brief introduction to the concept of a DOM, and then explains the rationale behind LINQ to XML’s DOM.
What Is a DOM?
Consider the following XML file:
<?xml version="1.0" encoding="utf-8"?> <customer id="123" status="archived"> <firstname>Joe</firstname> <lastname>Bloggs</lastname> </customer>
As with all XML files, we start with a declaration and then a root element, whose name is customer
. The customer
element has two attributes, each with a name (id
and status
) and value ("123"
and "archived"
). Within customer
, there are two child elements, firstname
and lastname
, each having ...
Get C# 9.0 in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.