LLINQ to XML
1 / 12
LESSON 01

Meet LINQ & LINQ to XML

Start with what LINQ actually is, then meet LINQ to XML — the in-memory XML programming interface that lets you build, query, and reshape XML trees using ordinary C# and query syntax instead of hand-rolled DOM code.

LINQ overviewLINQ to XML overviewProgramming overviewArchitecture

What LINQ actually gives you

LINQ (Language-Integrated Query) is a set of language and library features that let you write queries directly inside C#, against almost any kind of data.

Before LINQ, filtering, sorting, and projecting a collection meant hand-written loops — one style for arrays, another for a database, another again for XML. LINQ replaces all three with a single, consistent shape: a small set of operators (Where, Select, OrderBy, GroupBy, and friends) that work identically whether the source is a List<T>, a SQL table via EF Core, or — the subject of this course — an XML document.

Two syntaxes exist for the same underlying calls. Query syntax reads like SQL (from … where … select); method syntax chains extension methods. They compile to the same IL, so pick whichever reads more clearly for a given query — nested joins and grouping usually favor query syntax, simple filters usually favor method syntax.

LinqBasics.cs
// Query syntax
var expensive = from p in products
                 where p.Price > 100
                 orderby p.Price descending
                 select p.Name;

// Method syntax — same query, same compiled result
var expensive2 = products
    .Where(p => p.Price > 100)
    .OrderByDescending(p => p.Price)
    .Select(p => p.Name);
Why it matters hereEvery LINQ to XML lesson in this course leans on this same operator set. Once you can write Where/Select over a List<int>, you already know most of the syntax you'll use to query an XML tree — only the source changes.

What LINQ to XML adds System.Xml.Linq

LINQ to XML is an in-memory, LINQ-enabled XML programming interface, shipped in the System.Xml.Linq namespace since .NET Framework 3.5 and unchanged in shape through .NET 10.

It brings an entire XML document into memory as a tree of lightweight objects — XDocument, XElement, XAttribute, XComment, and a few others — and lets you query that tree with the exact LINQ operators you just saw, and mutate it with methods like Add, Remove, and ReplaceWith.

Compared to the older System.Xml DOM API (XmlDocument), LINQ to XML is deliberately smaller and friendlier: fewer node types, static Load/Parse methods instead of instance-based parsing, and — most importantly — first-class LINQ query support. Lesson 2 covers that comparison in depth; for now, just know that LINQ to XML is the modern default for XML work in .NET.

LOAD

Load or parse

Read XML from a file, stream, URL, or string into an in-memory tree.

QUERY

Query with LINQ

Use Where/Select/axes like Descendants() to pull out elements and attributes.

BUILD

Functional construction

Construct whole trees declaratively by nesting constructor calls.

EDIT

Modify in place

Add, remove, or replace nodes and attributes on the live tree.

SAVE

Serialize

Write the tree back out to a file, stream, or string.

VALIDATE

XSD validation

Check a tree against a schema via extension methods.

The object model, click to explore

These five pieces cooperate every time you touch LINQ to XML. Click a node to see its role.

{ }
Your C# code
Xdoc
XDocument
Xel
XElement tree
LINQ
Query operators
.xml
File / stream

Watch a query run, end to end

Press run to trace a query from LINQ expression down to the elements it produces.

Sample query
doc.Descendants("book").Where(b => (int)b.Attribute("year") > 2020)

A first taste of functional construction

You'll meet this pattern properly in Lesson 3, but it's worth seeing once here: building an XML tree is just nesting object constructors, innermost first.

FirstTree.cs
using System.Xml.Linq;

XElement catalog = new XElement("catalog",
    new XElement("book",
        new XAttribute("year", 2024),
        new XElement("title", "Modern XML in .NET"),
        new XElement("price", 39.99)
    )
);

Console.WriteLine(catalog);
Key ideaThere is no separate "create document, then append" step. The tree is fully described by the shape of the constructor calls — this is exactly what the docs call functional construction, and it's the single biggest ergonomic win over the older DOM API.

Practice

  1. Write a short LINQ query (query or method syntax) that filters a List<int> for even numbers and squares them.
  2. Click through all five architecture nodes above and, in your own words, describe what each one is responsible for.
  3. Run the query trace widget and identify which step is where your Where clause actually executes.
LESSON 02

LINQ to XML vs. DOM & other XML technologies

Before committing to LINQ to XML, it helps to see exactly what it replaces and what it doesn't. This lesson compares it head-to-head with the classic W3C DOM (XmlDocument) and positions it against XPath, XQuery, XSLT, and streaming readers.

LINQ to XML vs. DOMvs. other XML technologies

Building a tree: bottom-up vs. declarative

The DOM (System.Xml's XmlDocument) builds trees bottom-up: create a document, create elements, then explicitly append each one.

LINQ to XML replaces that with functional construction — nested constructor calls that mirror the shape of the resulting XML. There's no document object required to start, and no separate "append" step.

DomBuild.cs
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("catalog");
doc.AppendChild(root);

XmlElement book = doc.CreateElement("book");
XmlAttribute year = doc.CreateAttribute("year");
year.Value = "2024";
book.Attributes.Append(year);
root.AppendChild(book);
LinqXmlBuild.cs
XElement root = new XElement("catalog",
    new XElement("book",
        new XAttribute("year", 2024)
    )
);

Six lines shrink to four, but the bigger win is structural: the LINQ to XML version's indentation already looks like the XML it produces. That readability compounds on deeply nested documents.

Key structural differences reference table

AspectDOM (System.Xml)LINQ to XML
LoadingInstance methods: doc.Load(path)Static methods: XElement.Load(path)
QueryingXPath strings via SelectNodesNative LINQ query operators
Renaming a nodeCreate new node, copy children overSet the Name property directly
NamespacesManual prefix managementPrefixes auto-assigned on save; work mostly with XName
WhitespaceDedicated XmlWhitespace node typeStored as a plain XText node
Entities / DTDPreserved as distinct nodesExpanded on load; not separately represented
FragmentsXmlDocumentFragment typeJust an IEnumerable<XNode> from a query
AnnotationsNot built inExtensible per-node annotations for app metadata
Why the entity change is safeSupport for entities and entity references was intentionally dropped. Entity handling is complex and rarely used in modern XML; LINQ to XML expands all DTD entities as the tree loads, trading a rarely-needed feature for a simpler, faster API.

Where LINQ to XML sits among XML technologies

LINQ to XML isn't the only way to work with XML in .NET — it's the right default for most in-memory scenarios, but three other technologies still have their place.

LINQ to XML's query capability is functionally comparable to XPath and XQuery — you can express the same selections — but the syntax is entirely different: ordinary, strongly-typed C# instead of a separate query string language. That gives you compile-time checking and full debugger support, at the cost of losing a few XPath idioms you'd need to reproduce with LINQ operators.
XSLT declaratively transforms one XML document into another (or into HTML/text) using a separate stylesheet document. LINQ to XML does the same job imperatively, in C#, using functional construction plus queries. For one-off or C#-integrated transforms, LINQ to XML is usually simpler; for transforms driven by externally-supplied, swappable stylesheets, XSLT still wins.
XmlReader and XmlWriter are forward-only, low-allocation, streaming APIs — they never hold the whole document in memory. LINQ to XML can actually be layered on top of a reader (via XNode.ReadFrom) to stream large documents element-by-element while still getting LINQ to XML's object model for each chunk. Lesson 9 (Performance) covers this pattern in depth.
Schema validation isn't a competitor — LINQ to XML supports it directly via extension methods in System.Xml.Schema, letting you validate a tree against an XSD and optionally populate it with the post-schema-validation infoset (PSVI). Covered in Lesson 11 (Advanced).

Practice

  1. Rewrite the DOM snippet above so it also adds a <title> child, then do the same in LINQ to XML — compare line counts.
  2. Name one scenario where you'd still reach for XmlReader instead of loading a full XDocument.
LESSON 03

XML Trees: the object model

Every LINQ to XML program manipulates one data structure: a tree of nodes. This lesson covers the node hierarchy, functional construction in depth, XName/XAttribute mechanics, and how to load a tree from files, streams, or strings.

XML treesXNode hierarchyFunctional constructionLoading & parsing

The node hierarchy

Everything in a LINQ to XML tree derives from XObject. The nodes you'll touch daily form a small, flat hierarchy.

TypeRepresentsNotes
XDocumentAn entire XML documentOptional wrapper; holds one root XElement plus declaration/DOCTYPE/top-level comments
XElementAn element (a tag)Can have attributes, child nodes, and a text value; the workhorse type
XAttributeA name="value" pairNot an XNode — attributes aren't part of the sibling/child chain
XTextCharacter dataWhitespace is stored here too — there's no separate whitespace node type
XComment<!-- comment -->Valid at document or element level
XProcessingInstruction<?target data?>Rarely needed outside document-level metadata
XCData<![CDATA[ … ]]>A specialized XText subtype for CDATA sections

XDocument, XElement, XComment, XText, and XProcessingInstruction all derive from XNode, which gives them a place in the tree (Parent, NextNode, PreviousNode). XAttribute deliberately does not derive from XNode — attributes hang off an element but aren't siblings of its child nodes.

Practical rule of thumbMost real programs barely touch XDocument at all. If you don't need an XML declaration, a DOCTYPE, or root-level comments, working directly with a root XElement is perfectly idiomatic and slightly simpler.

Functional construction, in depth

The XElement and XDocument constructors accept a params object[] of content — strings, numbers, other elements, attributes, or even IEnumerable sequences of any of those, all mixed freely.

FunctionalConstruction.cs
using System.Xml.Linq;

var authors = new[] { "A. Novak", "R. Singh" };

XElement book = new XElement("book",
    new XAttribute("isbn", "978-0-13-468599-1"),
    new XAttribute("year", 2024),
    new XElement("title", "Modern XML in .NET"),
    new XElement("authors",
        authors.Select(name => new XElement("author", name))   // IEnumerable content
    ),
    new XElement("price",
        new XAttribute("currency", "USD"),
        49.99m
    )
);

Two things make this powerful. First, content can be any depth of nesting — the tree structure in code visually matches the tree structure of the output XML. Second, an IEnumerable<XElement> is flattened automatically, so projecting a collection with Select directly into an element's content is idiomatic — this is how LINQ to XML transforms one shape of tree into another, often called an XML-to-XML transform.

Common trapPassing the same XElement instance into two different parents doesn't share it — LINQ to XML clones a node when it detects it already has a parent, so each parent ends up with its own independent copy. Don't rely on later mutating one to affect the other.

Names: XName and value typing

Every element and attribute has an XName — a namespace-aware name — but you almost never construct one explicitly; a plain string is implicitly converted for you.

XNameAndValues.cs
// Implicit string -> XName conversion — the common case
XElement e = new XElement("price", 49.99m);

// Reading typed values back out via explicit casts on XElement/XAttribute
decimal price = (decimal)e;                 // element value cast
int year       = (int)book.Attribute("year");
DateTime? pub  = (DateTime?)book.Attribute("published"); // null-safe if missing

// Explicit XName construction (rarely needed directly)
XName priceName = XName.Get("price");

These casts are one of the most convenient parts of the API: XElement and XAttribute define explicit conversion operators to string, int, double, decimal, bool, DateTime, and their nullable equivalents. Casting to a nullable type on a missing attribute returns null instead of throwing — casting to a non-nullable type on a missing attribute throws NullReferenceException, so prefer the nullable cast when a value might be absent.

Loading and parsing existing XML

Both XElement and XDocument expose the same static entry points for getting XML into memory.

LoadFile.cs
XElement root = XElement.Load("catalog.xml");
XDocument doc  = XDocument.Load("catalog.xml");
ParseString.cs
string xml = "<book year=\"2024\"><title>Sample</title></book>";
XElement book = XElement.Parse(xml);
LoadStream.cs
using FileStream fs = File.OpenRead("catalog.xml");
XElement root = XElement.Load(fs);

// Also supports TextReader and XmlReader overloads
using XmlReader xr = XmlReader.Create("catalog.xml");
XElement fromReader = XElement.Load(xr);
LoadAsync.cs
await using FileStream fs = File.OpenRead("catalog.xml");
XElement root = await XElement.LoadAsync(fs, LoadOptions.None, cancellationToken: default);

By default, whitespace-only text nodes between elements are collapsed and line info is discarded. Pass LoadOptions.PreserveWhitespace to keep insignificant whitespace, or LoadOptions.SetLineInfo to retain source line/column data for diagnostics — useful when reporting validation errors back to a user.

Practice

  1. Build a small <team> tree with functional construction, feeding a List<string> of player names in through Select.
  2. Load an XML string with XElement.Parse, then read one attribute as an int and one as a nullable DateTime that isn't present — confirm you get null rather than an exception.
LESSON 04

Working with XML Namespaces

Namespaces are the part of XML programming developers dread most. LINQ to XML simplifies them dramatically by removing prefix bookkeeping from your code entirely — you work with fully-qualified names and let serialization pick prefixes for you.

XNamespaceQualified namesDefault namespacesPrefixes

The core idea: names, not prefixes

In raw XML, a namespace is expressed through a prefix bound to a URI (xmlns:b="http://example.com/books"). LINQ to XML deliberately hides prefixes from your working model — you compare and construct elements by their expanded name: namespace URI plus local name, exposed as an XNamespace + local-name pair combined into an XName.

Namespaces.cs
XNamespace ns = "http://example.com/books";

XElement catalog = new XElement(ns + "catalog",
    new XElement(ns + "book",
        new XAttribute("year", 2024),           // unqualified — attributes default to NO namespace
        new XElement(ns + "title", "Modern XML in .NET")
    )
);

Console.WriteLine(catalog);
// <catalog xmlns="http://example.com/books">
//   <book year="2024">
//     <title>Modern XML in .NET</title>
//   </book>
// </catalog>

The ns + "book" syntax uses XNamespace's overloaded + operator to build an XName — read it as "the name book, in namespace ns". Notice LINQ to XML chose to emit this as one default-namespace declaration on the root rather than repeating a prefix on every element; you didn't have to ask for that.

The single most common bugUnqualified attributes are not in the element's default namespace — per the XML namespaces spec, attributes only belong to a namespace if explicitly prefixed. Writing new XAttribute(ns + "year", 2024) when you meant a plain "year" attribute (or vice-versa when querying) is the number one namespace mistake.

Querying namespaced XML

Whether you're building or querying, the namespace has to match exactly — a local name string alone will never match a namespaced element.

QueryNamespaced.cs
XNamespace ns = "http://example.com/books";
XElement catalog = XElement.Load("catalog.xml");

// Correct — namespace-qualified
var titles = catalog.Descendants(ns + "title").Select(t => t.Value);

// Wrong — silently matches nothing, no exception
var wrong = catalog.Descendants("title");
Key habitDeclare one static readonly XNamespace per namespace you work with, near the top of the file or in a small constants class, and reuse it everywhere. It keeps the URI in exactly one place and makes namespace mismatches easy to spot in a diff.

Multiple namespaces & explicit prefixes

A document can mix several namespaces, and sometimes you do need a specific, human-chosen prefix — most commonly for XML that must exactly match an external schema.

ExplicitPrefix.cs
XNamespace atom = "http://www.w3.org/2005/Atom";
XNamespace app  = "http://www.w3.org/2007/app";

XElement entry = new XElement(atom + "entry",
    new XAttribute(XNamespace.Xmlns + "atom", atom),   // force a named prefix
    new XAttribute(XNamespace.Xmlns + "app", app),
    new XElement(atom + "title", "Entry Title"),
    new XElement(app + "control",
        new XElement(app + "draft", "yes")
    )
);

Adding an XAttribute whose name is built from XNamespace.Xmlns + "atom" is exactly how you request the literal prefix atom: instead of letting LINQ to XML auto-generate one (typically p1, p2, …) or fall back to a default namespace declaration.

Namespace cheat sheet

GoalCode
Declare a namespaceXNamespace ns = "uri";
Qualify an element/attribute namens + "localName"
No namespace, explicitlyXNamespace.None + "localName" (equivalent to a bare string)
Force a specific prefixnew XAttribute(XNamespace.Xmlns + "p", ns)
Read an element's namespace backelement.Name.Namespace
Read just the local nameelement.Name.LocalName

Practice

  1. Build an element tree in a custom namespace, then write a query using Descendants that correctly finds a nested element by its qualified name.
  2. Force an explicit prefix on that namespace and confirm the serialized XML uses your chosen prefix instead of a default namespace declaration.
LESSON 05

Serializing XML Trees

Getting a tree back out as text or bytes — to a file, a string, or a stream — with control over encoding, indentation, and declarations.

Save / ToStringFormatting optionsEncodingXmlWriter interop

The three output targets

XElement and XDocument both expose Save overloads plus ToString(), covering every common destination.

SaveFile.cs
catalog.Save("catalog.xml");                 // pretty-printed by default
catalog.Save("catalog.min.xml", SaveOptions.DisableFormatting);
ToStringOutput.cs
string pretty  = catalog.ToString();                              // indented
string compact = catalog.ToString(SaveOptions.DisableFormatting); // single line
SaveStream.cs
using FileStream fs = File.Create("catalog.xml");
catalog.Save(fs);

using XmlWriter xw = XmlWriter.Create("catalog.xml", new XmlWriterSettings { Indent = true });
catalog.Save(xw);   // full control via XmlWriterSettings
SaveAsync.cs
await using FileStream fs = File.Create("catalog.xml");
await catalog.SaveAsync(fs, SaveOptions.None, cancellationToken: default);

Routing through an explicit XmlWriter is the escape hatch whenever Save's two built-in options (SaveOptions.None for pretty-printed, SaveOptions.DisableFormatting for compact) aren't enough — for example, to control the newline character, quote style, or omit the XML declaration.

Encoding and the XML declaration gotcha

A subtlety trips up almost everyone the first time: XDocument.Save(string path) writes UTF-8 with a declaration, but ToString() never includes a declaration at all, and Save(Stream) honors the encoding you specify.

EncodingControl.cs
var doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    catalog
);

// Saving to a path: the declaration above is honored
doc.Save("catalog.xml");

// ToString() NEVER includes the XML declaration, by design —
// it's meant for embedding fragments, not standalone documents
string s = doc.ToString();   // starts directly with <catalog>...
Watch for thisIf you need a declaration in a string, you must add it manually — ToString() strips it unconditionally, even if the XDocument has an explicit XDeclaration. This is intentional: ToString() is designed to produce embeddable XML fragments.

Controlling whitespace on save

By default, Save and ToString re-indent the tree for readability, which can subtly change whitespace-sensitive content (like <pre>-style text). Pair the load and save options to round-trip exactly.

RoundTrip.cs
// Preserve original whitespace on the way in...
XElement doc = XElement.Load("source.xml", LoadOptions.PreserveWhitespace);

// ...and don't let Save re-indent it on the way out
doc.Save("copy.xml", SaveOptions.DisableFormatting);
Rule of thumbFor config files and human-authored XML, keep default formatting for readability. For byte-exact round-tripping (signing, hashing, diffing against source) always pair PreserveWhitespace on load with DisableFormatting on save.

Practice

  1. Save the same tree three ways — ToString(), Save(path), and Save(XmlWriter) with custom settings — and diff the outputs.
  2. Round-trip a document containing meaningful inline whitespace without losing a single space.
LESSON 06

LINQ to XML Axes

Axis methods are how you navigate a tree — analogous to XPath's axes (child, descendant, ancestor, following-sibling) but expressed as ordinary methods returning IEnumerable<T>, ready to feed straight into LINQ.

Elements() / Element()Descendants()Ancestors()Nodes() & siblings

Why axes exist

A tree gives you Parent and a couple of raw node-chain properties, but real navigation — "all descendant <book> elements", "every ancestor up to the root", "the next sibling element" — needs dedicated traversal methods. That's what axes are: a family of methods, all returning sequences, all composable with Where/Select.

SampleTree.xml
<catalog>
  <book year="2019"><title>Old Edition</title></book>
  <book year="2024">
    <title>Modern XML in .NET</title>
    <authors>
      <author>A. Novak</author>
      <author>R. Singh</author>
    </authors>
  </book>
</catalog>

The axis family

Elements.cs
IEnumerable<XElement> books = catalog.Elements("book");   // all direct <book> children
XElement? first = catalog.Element("book");                 // just the first, or null
The plain, no-suffix form only looks at direct children — it never descends further. Element() (singular) returns the first match or null; Elements() (plural) returns all matches as a sequence.
Descendants.cs
// Finds <author> no matter how deeply nested
IEnumerable<XElement> authors = catalog.Descendants("author");

// DescendantsAndSelf() includes the starting element itself
IEnumerable<XElement> withSelf = catalog.DescendantsAndSelf("catalog");
This is the axis you reach for most often — it walks the whole subtree in document order, regardless of depth, and is the natural way to say "find every X anywhere under here."
Ancestors.cs
XElement author = catalog.Descendants("author").First();
IEnumerable<XElement> chain = author.Ancestors();          // authors, book, catalog — nearest first
XElement? enclosingBook = author.Ancestors("book").FirstOrDefault();
Ancestors() walks up from a node's parent to the root, nearest ancestor first — handy for "find the enclosing book for this author" without manually chasing .Parent.Parent chains.
Nodes.cs
// Unlike Elements(), Nodes() includes text, comments, everything — not just elements
IEnumerable<XNode> allChildren = title.Nodes();
IEnumerable<XNode> allDescendantNodes = catalog.DescendantNodes();
Use Nodes()/DescendantNodes() instead of Elements()/Descendants() when text nodes, comments, or processing instructions matter — for example, when preserving mixed content (elements interleaved with free text).
Siblings.cs
XElement second = catalog.Elements("book").Skip(1).First();
XNode?  next    = second.NextNode;
XNode?  prev    = second.PreviousNode;
XElement? nextBook = second.ElementsAfterSelf("book").FirstOrDefault();
There's no dedicated "following-sibling" axis method family beyond NodesAfterSelf()/ElementsAfterSelf() and their …BeforeSelf() counterparts — small but useful for "the item right after this one" queries.

Choosing the right axis performance-relevant

You want…Use
Direct children onlyElements() / Elements(name)
Anywhere in the subtreeDescendants(name)
Include the starting node tooDescendantsAndSelf(name)
Text/comments includedNodes() / DescendantNodes()
Parent chain to rootAncestors(name)
Just attributesAttributes(name)
Performance noteCalling Descendants() when you only need direct children forces a full subtree walk for no reason. On large documents, prefer the narrowest axis that answers the question — this is expanded on in Lesson 9.

Practice

  1. Using the sample tree above, write one query with Elements() and one with Descendants() that return different results — explain why.
  2. Given an <author> element, write a one-line expression that returns its enclosing <book>'s year attribute.
LESSON 07

Querying XML Trees

Axes give you sequences of nodes; LINQ operators turn those sequences into answers — filtered lists, grouped summaries, joined data, projected shapes. This lesson works through the query patterns you'll use constantly.

Where / SelectGroupingJoining two treesProjecting to objects

Filter, then project

The single most common LINQ to XML query shape: descend to the elements you care about, filter with Where, then Select out exactly the shape you need — often a plain C# object, not more XML.

FilterProject.cs
record BookSummary(string Title, int Year, decimal Price);

XElement catalog = XElement.Load("catalog.xml");

var recentAffordable =
    from book in catalog.Elements("book")
    where (int)book.Attribute("year") >= 2020
       && (decimal)book.Element("price") < 50
    select new BookSummary(
        (string)book.Element("title"),
        (int)book.Attribute("year"),
        (decimal)book.Element("price")
    );

foreach (var b in recentAffordable)
    Console.WriteLine($"{b.Title} ({b.Year}) — ${b.Price}");

Because the casts inside the where clause pull typed values straight from attributes/elements, the rest of the pipeline never touches XML types again — you're working with strongly-typed records from that point on.

Grouping

Grouping XML data works exactly like grouping any other sequence — GroupBy doesn't care that the source happens to be XElement.

GroupBooks.cs
var byDecade =
    from book in catalog.Descendants("book")
    let year = (int)book.Attribute("year")
    group book by (year / 10) * 10 into g
    orderby g.Key
    select new { Decade = g.Key, Count = g.Count(), Titles = g.Select(b => (string)b.Element("title")) };

foreach (var d in byDecade)
    Console.WriteLine($"{d.Decade}s: {d.Count} book(s)");
TipThe let clause (let year = …) computes a value once and reuses it in both the grouping key and later clauses — cleaner than repeating the same attribute cast three times.

Joining two XML sources

LINQ's join works across two independent element sequences — useful when related data lives in separate documents or separate parts of one tree, keyed by a shared id.

JoinTrees.cs
XElement books   = XElement.Load("books.xml");     // <book id="b1" authorId="a1">...</book>
XElement authors = XElement.Load("authors.xml");   // <author id="a1">A. Novak</author>

var joined =
    from b in books.Elements("book")
    join a in authors.Elements("author")
      on (string)b.Attribute("authorId") equals (string)a.Attribute("id")
    select new {
        Title  = (string)b.Element("title"),
        Author = a.Value
    };

Projecting back to XML

A query doesn't have to leave XML — Select can construct new XElements, letting you reshape one document into another entirely with LINQ. This bridges directly into Lesson 10's transform patterns.

ProjectToXml.cs
XElement summary = new XElement("summary",
    from book in catalog.Elements("book")
    where (int)book.Attribute("year") >= 2020
    select new XElement("entry",
        new XAttribute("year", (int)book.Attribute("year")),
        book.Element("title").Value
    )
);
Key ideaA LINQ query returning XElements can be dropped straight into another element's constructor as content — query and construction compose seamlessly, which is what makes LINQ to XML transforms so compact compared to XSLT for C#-native scenarios.

Practice

  1. Write a query that groups books by author and counts how many each author wrote.
  2. Join two small in-memory trees (orders and customers) on a shared id attribute and project the combined result.
  3. Take any query from this lesson and rewrite its result as newly constructed XML instead of an anonymous type.
LESSON 08

Modifying XML Trees

Once a tree is in memory, you can mutate it in place — add nodes, remove them, replace whole subtrees, or update values and attributes — without rebuilding from scratch.

Add / AddFirstRemoveReplaceWithSetValue / SetAttributeValue

Adding content

Every insertion method accepts the same flexible params object[] content model as the constructors — strings, elements, attributes, or sequences of them.

Adding.cs
XElement catalog = XElement.Load("catalog.xml");

// Append as the last child
catalog.Add(new XElement("book",
    new XAttribute("year", 2025),
    new XElement("title", "New Arrival")
));

// Insert as the first child instead
catalog.AddFirst(new XComment(" featured item "));

// Add or overwrite a single attribute — safer than manual Attribute()+SetValue
catalog.SetAttributeValue("updated", DateTime.UtcNow.ToString("O"));

SetAttributeValue is worth calling out: pass null as the value and it removes the attribute if present, doing nothing if it wasn't there — a convenient "set-or-clear" in one call that avoids null-checking yourself.

Removing content

Removing.cs
// Remove one specific element
catalog.Elements("book").First(b => (int)b.Attribute("year") < 2000).Remove();

// Remove every matching element — materialize with ToList() first!
catalog.Elements("book")
       .Where(b => (int)b.Attribute("year") < 2000)
       .ToList()          // avoid mutating a sequence you're still enumerating
       .ForEach(b => b.Remove());

// Or use the batch-safe helper, which handles this internally
catalog.Elements("book").Where(b => (int)b.Attribute("year") < 2000).Remove();
Classic bug: modifying while enumeratingCalling .Remove() inside a foreach over a live LINQ to XML query throws InvalidOperationException — the query is still lazily walking the collection you're mutating. Either materialize first with .ToList(), or use the static batch Extensions.Remove(IEnumerable<XElement>) helper (called as query.Remove() above), which is specifically designed to remove a whole matched sequence safely.

Replacing content

Replacing.cs
XElement oldPrice = book.Element("price");

// Swap one element for a differently-shaped one
oldPrice.ReplaceWith(
    new XElement("price", new XAttribute("currency", "EUR"), 45.00m)
);

// Replace just this element's children, keeping the element itself
book.ReplaceNodes(
    new XElement("title", "Revised Title"),
    new XElement("price", 44.99m)
);

ReplaceWith swaps the node itself (and everything under it) for new content, in the same tree position. ReplaceNodes keeps the element but replaces only what's inside it — reach for this when you want to keep the element's own attributes untouched while overhauling its children.

In-place value updates

SetValue.cs
XElement price = book.Element("price");
price.Value = "39.99";                 // string assignment
price.SetValue(39.99m);                // typed — formats correctly for you

book.SetElementValue("title", "Updated Title");  // creates the element if missing
Prefer SetValue over the Value setter for non-stringsSetValue accepts any of the types XElement knows how to cast (numbers, DateTime, bool) and formats them using invariant, XML-Schema-compatible formatting — safer than manually calling .ToString() and assigning to .Value, which can produce culture-dependent output on a misconfigured thread.

Practice

  1. Load a catalog, remove every book older than a given year using the batch-safe pattern, and save the result.
  2. Replace one book's <price> element entirely, then update another book's price in place with SetValue — compare the two approaches.
LESSON 09

Performance

LINQ to XML trades some memory and CPU for ergonomics — an entire document lives in memory as objects. This lesson covers when that trade-off matters, and how to avoid the tree entirely for very large documents by streaming.

Deferred executionStreaming with XmlReaderAvoiding repeated walksMemory footprint

Deferred execution — friend and foot-gun

Like all LINQ, axis methods and query operators return lazily-evaluated IEnumerable<T> sequences — nothing actually walks the tree until you enumerate (via foreach, .ToList(), .Count(), etc.).

Deferred.cs
var query = catalog.Descendants("book").Where(b => (int)b.Attribute("year") > 2020);

// Nothing has executed yet — query is just a description

int countA = query.Count();   // walks the tree once
int countB = query.Count();   // walks the tree AGAIN — same work repeated

// Fix: materialize once if you'll use the result more than once
var matches = query.ToList();
int c1 = matches.Count;       // no re-walk
int c2 = matches.Count;
Watch for thisRe-enumerating the same un-materialized query multiple times silently repeats the entire traversal each time — on a large tree, this is the single most common accidental performance bug in LINQ to XML code. If a query result is used more than once, call .ToList() or .ToArray() explicitly.

Streaming large documents with XmlReader

Loading a multi-hundred-megabyte XML file with XElement.Load means holding the entire tree in memory at once. For very large or unbounded documents, stream through it and materialize only small pieces at a time using XNode.ReadFrom.

StreamingRead.cs
static IEnumerable<XElement> StreamBooks(string path)
{
    using XmlReader reader = XmlReader.Create(path);
    reader.MoveToContent();
    reader.ReadStartElement("catalog");

    while (reader.NodeType != XmlNodeType.EndElement)
    {
        XElement book = (XElement)XNode.ReadFrom(reader);   // reads ONE <book> subtree
        yield return book;                                   // caller processes and discards it
    }
}

// Only one <book> element is ever in memory at a time
foreach (XElement book in StreamBooks("huge-catalog.xml"))
{
    if ((int)book.Attribute("year") > 2020)
        Console.WriteLine((string)book.Element("title"));
}

This hybrid pattern gives you the best of both worlds: XmlReader's constant memory footprint for walking the document, plus LINQ to XML's convenient object model and casts for each individual chunk you pull out.

Other practical performance habits

AXIS CHOICE

Narrowest axis wins

Prefer Elements() over Descendants() whenever you only need direct children — a full subtree walk costs more the deeper the tree.

CACHING

Cache repeated lookups

If the same Descendants(name) result feeds several downstream queries, materialize it once instead of re-querying the source tree.

BUILD

Functional construction is cheap

Building a tree via nested constructors is fast and allocation-light compared to incremental Add() calls in a loop.

WRITE

Stream writes too

XStreamingElement defers content generation until serialization, letting you write huge generated documents without holding them all in memory — see Lesson 10.

Practice

  1. Take a query you wrote in Lesson 7 and identify whether it's enumerated more than once anywhere in a hypothetical calling method — fix it if so.
  2. Sketch (in comments, no need to run it) a streaming reader for a large <orders> document that yields one <order> at a time.
LESSON 10

Advanced LINQ to XML Programming

Beyond the everyday query/build/modify cycle: streaming output with XStreamingElement, deep transforms, annotations, XSD validation, and interop with XmlDocument and XPath.

XStreamingElementTree transformsAnnotationsXSD validationDOM & XPath interop

XStreamingElement — deferred output generation

A regular XElement evaluates its content immediately when constructed. XStreamingElement instead captures the content as a deferred query, evaluated only once, at the moment it's written out — useful for generating very large documents from a data source without materializing the whole thing in memory first.

StreamingOutput.cs
IEnumerable<Order> orders = GetOrdersFromDatabase();  // could be millions of rows

XStreamingElement root = new XStreamingElement("orders",
    orders.Select(o => new XElement("order",
        new XAttribute("id", o.Id),
        new XElement("total", o.Total)
    ))
);

root.Save("orders.xml");   // orders are pulled and written one at a time, never all in memory
Key difference from XElementAn XStreamingElement can only be written once — it has no persistent tree to re-query or navigate afterward. Use it purely as an output pipe, not as something you'll later call Descendants() on.

Tree-to-tree transforms

Combining functional construction with querying lets you reshape an entire document — the LINQ to XML equivalent of an XSLT stylesheet, expressed as C#.

Transform.cs
// Flatten a nested <catalog>/<book>/<authors>/<author> tree
// into a flat <index> of author -> title pairs
XElement index = new XElement("index",
    from book in catalog.Descendants("book")
    from author in book.Descendants("author")
    select new XElement("entry",
        new XAttribute("author", author.Value),
        new XAttribute("title", (string)book.Element("title"))
    )
);

The nested from clauses here perform a flattening join — one row per author, even though authors are nested two levels under each book. This "reshape via nested query + construction" idiom covers most transform scenarios that would otherwise need XSLT.

Annotations — attaching app-specific metadata

Any XObject can carry arbitrary CLR objects as annotations — data that travels with the node but never serializes into the XML itself.

Annotations.cs
class ValidationInfo { public bool IsValid; public string? Error; }

book.AddAnnotation(new ValidationInfo { IsValid = false, Error = "Missing ISBN" });

var info = book.Annotation<ValidationInfo>();
if (info is { IsValid: false })
    Console.WriteLine($"Problem: {info.Error}");

book.RemoveAnnotations<ValidationInfo>();
Typical usesTracking whether a node came from user input vs. a default, caching a validation result, associating a UI control with the node it renders — anything you'd otherwise need a parallel dictionary keyed by node identity for.

XSD schema validation

XsdValidate.cs
using System.Xml.Schema;

XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add(null, "catalog.xsd");

XDocument doc = XDocument.Load("catalog.xml");
bool isValid = true;

doc.Validate(schemas, (o, e) =>
{
    isValid = false;
    Console.WriteLine($"{e.Severity}: {e.Message}");
});

Console.WriteLine(isValid ? "Valid" : "Invalid");

The validation event handler fires once per issue, so you get every violation in one pass rather than stopping at the first one — pass null for silent validation if you only care about the boolean result via a caught XmlSchemaValidationException.

Interop: DOM and XPath

You don't have to choose LINQ to XML exclusively — it converts cleanly to and from XmlDocument, and supports XPath expressions directly via extension methods for the rare query that's genuinely easier to express as XPath.

ToDom.cs
using System.Xml;

XmlDocument domDoc = new XmlDocument();
using (XmlReader reader = catalog.CreateReader())
    domDoc.Load(reader);
FromDom.cs
XmlDocument domDoc = GetLegacyDomDocument();
XElement fromDom = XElement.Load(new XmlNodeReader(domDoc));
XPathExt.cs
using System.Xml.XPath;   // System.Xml.XPath.Extensions

XElement? first = catalog.XPathSelectElement("//book[@year>2020]");
IEnumerable<XElement> all = catalog.XPathSelectElements("//book[@year>2020]");

Practice

  1. Rewrite the streaming-output example to generate a large <log> document from an IEnumerable<LogEntry> without ever holding it all in memory.
  2. Attach and read back a custom annotation type on an element you construct yourself.
  3. Validate a small tree against a hand-written XSD and print every violation.
LESSON 11

LINQ to XML Security

XML parsers have a well-known attack surface: DTD-driven denial-of-service and information disclosure. This lesson covers what LINQ to XML does by default, what still needs your attention, and safe patterns for untrusted input.

XML bombs / entity expansionExternal entity resolutionSafe defaultsUntrusted input checklist

The core risk: DTDs and entity expansion

Historically, XML parsers that fully honor DTDs are vulnerable to two related attacks: entity expansion bombs (a small file that expands to gigabytes in memory via recursive entity references — the classic "billion laughs" attack) and XXE (XML External Entity attacks, where a DTD references an external file or URL, leaking local data or triggering server-side requests).

billion-laughs.xml
<!DOCTYPE lolz [
  <!ENTITY lol "lol">
  <!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
  <!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">
  <!-- ...continues, each level multiplying the previous by ~10x -->
]>
<lolz>&lol3;</lolz>

A handful of nested entity definitions like this can expand to gigabytes of text when parsed naively, exhausting memory before your code ever gets a chance to reject it.

What .NET does by default

Good newsSince .NET Framework 4.5.2 (and unchanged through .NET 10), XmlReader's default DtdProcessing is Prohibited — a document with an internal or external DTD throws an exception the moment one is encountered. Because XElement.Load/Parse use XmlReader internally, LINQ to XML inherits this safe-by-default behavior automatically. You do not need to configure anything extra to be protected against the "billion laughs" pattern in ordinary usage.

The risk reappears only when code explicitly constructs a more permissive XmlReaderSettings — most commonly by setting DtdProcessing = DtdProcessing.Parse to support some legacy document that genuinely needs entities. That's the configuration to scrutinize.

Dangerous.cs
// DANGEROUS if the source is untrusted — re-enables the attack surface
var settings = new XmlReaderSettings
{
    DtdProcessing = DtdProcessing.Parse,   // opts back into DTD/entity expansion
    XmlResolver = new XmlUrlResolver()     // AND allows resolving external URIs — XXE risk
};
using XmlReader reader = XmlReader.Create("untrusted.xml", settings);
XElement doc = XElement.Load(reader);      // now vulnerable

Safe patterns for untrusted input

SituationRecommendation
Plain XElement.Load(path)Already safe — default DTD prohibition applies
Must support DTDsSet MaxCharactersFromEntities to cap total expansion size, and set XmlResolver = null to block external entity/URI resolution entirely
Very large untrusted filesAlso cap with XmlReaderSettings.MaxCharactersInDocument before parsing begins
XSD validation of untrusted inputValidate against a known, trusted schema (Lesson 10) — never let the document supply its own schema location and auto-fetch it
SaferSettings.cs
var settings = new XmlReaderSettings
{
    DtdProcessing = DtdProcessing.Parse,
    MaxCharactersFromEntities = 10_000,   // hard cap on entity expansion size
    XmlResolver = null                     // never resolve external entities/URIs
};
using XmlReader reader = XmlReader.Create(untrustedStream, settings);
XElement doc = XElement.Load(reader);
Bottom lineFor the overwhelming majority of programs — reading config files, API payloads, or app-generated XML — the framework defaults are already safe, and no special code is required. The risk only exists if you (or a dependency) explicitly loosen XmlReaderSettings to accept DTDs from a source you don't fully trust.

Practice

  1. Confirm for yourself that loading the billion-laughs sample above with plain XElement.Load throws rather than hanging or exhausting memory.
  2. Write the XmlReaderSettings you'd use to accept a legacy DTD-based document from a partner you trust but still want to bound resource usage for.
LESSON 12

Sample XML Documents & Reference / Roadmap

A compact wrap-up lesson: the sample documents Microsoft's own docs reuse across examples, a one-page API reference for the types and methods this course covered, and where to go for the primary source material and future changes.

Sample XML documentsReferenceWhere to go next

Sample XML documents

The official docs reuse a small set of sample documents across most LINQ to XML examples — purchase orders, book catalogs, and customer/order lists. Recreating a similar shape locally is the fastest way to follow along with any example you encounter in the wild.

purchase-order.xml
<PurchaseOrder PurchaseOrderNumber="99503" OrderDate="2024-07-08">
  <Address Type="Shipping">
    <Name>Ellen Adams</Name>
    <City>Renton</City>
    <State>WA</State>
  </Address>
  <Items>
    <Item PartNumber="872-AA">
      <ProductName>Lawnmower</ProductName>
      <Quantity>1</Quantity>
      <USPrice>148.95</USPrice>
    </Item>
  </Items>
</PurchaseOrder>
SHAPE 1

Purchase order

One root, a nested Address, and a repeating Items/Item collection — good for practicing Descendants + attribute casts together.

SHAPE 2

Book catalog

Used throughout this course — books with attributes, nested authors, and prices; ideal for grouping/joining practice.

SHAPE 3

Customers & orders

Two related entity lists joined by id — the standard shape for practicing LINQ join queries across XML sources.

Practice suggestionRecreate all three shapes as small local files and re-run at least one query from Lessons 6–8 against each — different shapes surface different axis and join patterns.

Quick API reference

XDocumentWhole document: declaration, DOCTYPE, root element, top-level comments/PIs
XElementAn element — attributes, children, text value; the type you'll use most
XAttributeA name/value pair on an element; not part of the node chain
XName / XNamespaceNamespace-aware names; build with ns + "local"
XText / XCData / XCommentText, CDATA, and comment node types
XStreamingElementDeferred, write-once element for generating large output without buffering
Load(path/stream/reader)Static; parses into a new tree
Parse(string)Static; parses an in-memory XML string
Save(path/stream/writer)Serializes the tree; formats by default
ToString()Serializes to string; never includes a declaration
LoadOptions / SaveOptionsControl whitespace preservation and formatting
Elements() / Element()Direct children — all, or first-or-null
Descendants()Every level below, document order
Ancestors()Parent chain up to the root
Nodes() / DescendantNodes()Includes text/comments, not just elements
…AfterSelf() / …BeforeSelf()Sibling navigation
Add / AddFirstAppend or prepend content
RemoveDelete a node; batch-safe on a query result
ReplaceWith / ReplaceNodesSwap a node, or just its children
SetValue / SetAttributeValue / SetElementValueTyped in-place updates; null clears an attribute

Roadmap & where to go next non-teaching reference

LINQ to XML itself is a mature, stable API — it hasn't needed breaking changes since .NET Framework 3.5, and remains fully supported as-is through .NET 10 and C# 14. Ongoing improvement in this area of the platform tends to show up one level up the stack rather than in System.Xml.Linq directly:

LANGUAGE

C# 14 ergonomics

Features like extension members and first-class span types make helper code around LINQ to XML terser, without changing the XML API surface itself.

RUNTIME

JIT & AOT improvements

.NET 10's JIT and Native AOT work benefits any LINQ to XML-heavy code path indirectly through general throughput gains.

ADJACENT

System.Text.Json growth

For new greenfield data formats, many teams now reach for JSON by default — LINQ to XML remains the right tool specifically when the data is XML.

Primary sources for anything not covered hereThe authoritative reference for every type and member in this namespace is the System.Xml.Linq API reference on Microsoft Learn, plus the "LINQ to XML" section of the .NET docs this course was built from. When in doubt about an overload or edge case, that's the source of truth — this course teaches the concepts and patterns; the reference docs are the exhaustive member-by-member listing.

Practice

  1. Recreate the purchase-order sample locally and write one query per axis family (Elements, Descendants, Ancestors) against it.
  2. Pick one lesson from this course and, without looking back at it, rebuild its main code example from memory — then compare.