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.
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.
// 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);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 or parse
Read XML from a file, stream, URL, or string into an in-memory tree.
Query with LINQ
Use Where/Select/axes like Descendants() to pull out elements and attributes.
Functional construction
Construct whole trees declaratively by nesting constructor calls.
Modify in place
Add, remove, or replace nodes and attributes on the live tree.
Serialize
Write the tree back out to a file, stream, or string.
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.
Watch a query run, end to end
Press run to trace a query from LINQ expression down to the elements it produces.
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.
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);Practice
- Write a short LINQ query (query or method syntax) that filters a List<int> for even numbers and squares them.
- Click through all five architecture nodes above and, in your own words, describe what each one is responsible for.
- Run the query trace widget and identify which step is where your Where clause actually executes.
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.
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.
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);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
| Aspect | DOM (System.Xml) | LINQ to XML |
|---|---|---|
| Loading | Instance methods: doc.Load(path) | Static methods: XElement.Load(path) |
| Querying | XPath strings via SelectNodes | Native LINQ query operators |
| Renaming a node | Create new node, copy children over | Set the Name property directly |
| Namespaces | Manual prefix management | Prefixes auto-assigned on save; work mostly with XName |
| Whitespace | Dedicated XmlWhitespace node type | Stored as a plain XText node |
| Entities / DTD | Preserved as distinct nodes | Expanded on load; not separately represented |
| Fragments | XmlDocumentFragment type | Just an IEnumerable<XNode> from a query |
| Annotations | Not built in | Extensible per-node annotations for app metadata |
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.
Practice
- Rewrite the DOM snippet above so it also adds a <title> child, then do the same in LINQ to XML — compare line counts.
- Name one scenario where you'd still reach for XmlReader instead of loading a full XDocument.
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.
The node hierarchy
Everything in a LINQ to XML tree derives from XObject. The nodes you'll touch daily form a small, flat hierarchy.
| Type | Represents | Notes |
|---|---|---|
| XDocument | An entire XML document | Optional wrapper; holds one root XElement plus declaration/DOCTYPE/top-level comments |
| XElement | An element (a tag) | Can have attributes, child nodes, and a text value; the workhorse type |
| XAttribute | A name="value" pair | Not an XNode — attributes aren't part of the sibling/child chain |
| XText | Character data | Whitespace 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.
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.
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.
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.
// 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.
XElement root = XElement.Load("catalog.xml");
XDocument doc = XDocument.Load("catalog.xml");string xml = "<book year=\"2024\"><title>Sample</title></book>"; XElement book = XElement.Parse(xml);
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);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
- Build a small <team> tree with functional construction, feeding a List<string> of player names in through Select.
- 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.
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.
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.
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.
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.
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");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.
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
| Goal | Code |
|---|---|
| Declare a namespace | XNamespace ns = "uri"; |
| Qualify an element/attribute name | ns + "localName" |
| No namespace, explicitly | XNamespace.None + "localName" (equivalent to a bare string) |
| Force a specific prefix | new XAttribute(XNamespace.Xmlns + "p", ns) |
| Read an element's namespace back | element.Name.Namespace |
| Read just the local name | element.Name.LocalName |
Practice
- Build an element tree in a custom namespace, then write a query using Descendants that correctly finds a nested element by its qualified name.
- Force an explicit prefix on that namespace and confirm the serialized XML uses your chosen prefix instead of a default namespace declaration.
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.
The three output targets
XElement and XDocument both expose Save overloads plus ToString(), covering every common destination.
catalog.Save("catalog.xml"); // pretty-printed by default
catalog.Save("catalog.min.xml", SaveOptions.DisableFormatting);string pretty = catalog.ToString(); // indented string compact = catalog.ToString(SaveOptions.DisableFormatting); // single line
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 XmlWriterSettingsawait 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.
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>...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.
// 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);Practice
- Save the same tree three ways — ToString(), Save(path), and Save(XmlWriter) with custom settings — and diff the outputs.
- Round-trip a document containing meaningful inline whitespace without losing a single space.
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.
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.
<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
IEnumerable<XElement> books = catalog.Elements("book"); // all direct <book> children
XElement? first = catalog.Element("book"); // just the first, or null// 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");XElement author = catalog.Descendants("author").First();
IEnumerable<XElement> chain = author.Ancestors(); // authors, book, catalog — nearest first
XElement? enclosingBook = author.Ancestors("book").FirstOrDefault();// Unlike Elements(), Nodes() includes text, comments, everything — not just elements IEnumerable<XNode> allChildren = title.Nodes(); IEnumerable<XNode> allDescendantNodes = catalog.DescendantNodes();
XElement second = catalog.Elements("book").Skip(1).First();
XNode? next = second.NextNode;
XNode? prev = second.PreviousNode;
XElement? nextBook = second.ElementsAfterSelf("book").FirstOrDefault();Choosing the right axis performance-relevant
| You want… | Use |
|---|---|
| Direct children only | Elements() / Elements(name) |
| Anywhere in the subtree | Descendants(name) |
| Include the starting node too | DescendantsAndSelf(name) |
| Text/comments included | Nodes() / DescendantNodes() |
| Parent chain to root | Ancestors(name) |
| Just attributes | Attributes(name) |
Practice
- Using the sample tree above, write one query with Elements() and one with Descendants() that return different results — explain why.
- Given an <author> element, write a one-line expression that returns its enclosing <book>'s year attribute.
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.
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.
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.
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)");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.
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.
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
)
);Practice
- Write a query that groups books by author and counts how many each author wrote.
- Join two small in-memory trees (orders and customers) on a shared id attribute and project the combined result.
- Take any query from this lesson and rewrite its result as newly constructed XML instead of an anonymous type.
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.
Adding content
Every insertion method accepts the same flexible params object[] content model as the constructors — strings, elements, attributes, or sequences of them.
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
// 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();Replacing content
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
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 missingPractice
- Load a catalog, remove every book older than a given year using the batch-safe pattern, and save the result.
- Replace one book's <price> element entirely, then update another book's price in place with SetValue — compare the two approaches.
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 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.).
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;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.
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
Narrowest axis wins
Prefer Elements() over Descendants() whenever you only need direct children — a full subtree walk costs more the deeper the tree.
Cache repeated lookups
If the same Descendants(name) result feeds several downstream queries, materialize it once instead of re-querying the source tree.
Functional construction is cheap
Building a tree via nested constructors is fast and allocation-light compared to incremental Add() calls in a loop.
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
- 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.
- Sketch (in comments, no need to run it) a streaming reader for a large <orders> document that yields one <order> at a time.
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.
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.
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 memoryTree-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#.
// 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.
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>();XSD schema validation
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.
using System.Xml;
XmlDocument domDoc = new XmlDocument();
using (XmlReader reader = catalog.CreateReader())
domDoc.Load(reader);XmlDocument domDoc = GetLegacyDomDocument(); XElement fromDom = XElement.Load(new XmlNodeReader(domDoc));
using System.Xml.XPath; // System.Xml.XPath.Extensions
XElement? first = catalog.XPathSelectElement("//book[@year>2020]");
IEnumerable<XElement> all = catalog.XPathSelectElements("//book[@year>2020]");Practice
- Rewrite the streaming-output example to generate a large <log> document from an IEnumerable<LogEntry> without ever holding it all in memory.
- Attach and read back a custom annotation type on an element you construct yourself.
- Validate a small tree against a hand-written XSD and print every violation.
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.
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).
<!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
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 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 vulnerableSafe patterns for untrusted input
| Situation | Recommendation |
|---|---|
| Plain XElement.Load(path) | Already safe — default DTD prohibition applies |
| Must support DTDs | Set MaxCharactersFromEntities to cap total expansion size, and set XmlResolver = null to block external entity/URI resolution entirely |
| Very large untrusted files | Also cap with XmlReaderSettings.MaxCharactersInDocument before parsing begins |
| XSD validation of untrusted input | Validate against a known, trusted schema (Lesson 10) — never let the document supply its own schema location and auto-fetch it |
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);Practice
- Confirm for yourself that loading the billion-laughs sample above with plain XElement.Load throws rather than hanging or exhausting memory.
- 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.
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 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.
<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>Purchase order
One root, a nested Address, and a repeating Items/Item collection — good for practicing Descendants + attribute casts together.
Book catalog
Used throughout this course — books with attributes, nested authors, and prices; ideal for grouping/joining practice.
Customers & orders
Two related entity lists joined by id — the standard shape for practicing LINQ join queries across XML sources.
Quick API reference
| XDocument | Whole document: declaration, DOCTYPE, root element, top-level comments/PIs |
| XElement | An element — attributes, children, text value; the type you'll use most |
| XAttribute | A name/value pair on an element; not part of the node chain |
| XName / XNamespace | Namespace-aware names; build with ns + "local" |
| XText / XCData / XComment | Text, CDATA, and comment node types |
| XStreamingElement | Deferred, 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 / SaveOptions | Control 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 / AddFirst | Append or prepend content |
| Remove | Delete a node; batch-safe on a query result |
| ReplaceWith / ReplaceNodes | Swap a node, or just its children |
| SetValue / SetAttributeValue / SetElementValue | Typed 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:
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.
JIT & AOT improvements
.NET 10's JIT and Native AOT work benefits any LINQ to XML-heavy code path indirectly through general throughput gains.
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.
Practice
- Recreate the purchase-order sample locally and write one query per axis family (Elements, Descendants, Ancestors) against it.
- Pick one lesson from this course and, without looking back at it, rebuild its main code example from memory — then compare.