Chapter 10. LINQ to XML
The .NET Framework provides a number of APIs for working with XML
data. From Framework 3.5, 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, and a set of supplementary query
operators. In most scenarios, it can be considered a complete replacement
for the preceding W3C-compliant DOM, a.k.a.
In this chapter, we concentrate entirely on LINQ to XML. In the following chapter, we cover the more specialized XML types and APIs, including the forward-only reader/writer, the types for working with schemas, stylesheets and XPaths, and the legacy W3C-compliant DOM.
The LINQ to XML 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
All LINQ to XML types are defined in the
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" standalone="yes"?> <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. It has two attributes, each with a name (
status) and value (