IC Improve Code Recipes

Recipe 12.4 · C#

LINQ to XML for Documents Without Classes

Problem

Not every XML document deserves a class. You need three values from a configuration file, a quick transformation of a partner feed, or a small document built from a query. The old way meant XmlDocument, XPath strings and InnerText, or worse, building XML with string concatenation.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
// Not to copy: string-built XML breaks on "&" and "<" in data
string xml = "<Product><Name>" + product.Name + "</Name>" +
             "<Price>" + product.Price + "</Price></Product>";

// Not to copy: NullReferenceException when a node is missing
var doc = new XmlDocument();
doc.Load(path);
string name = doc.SelectSingleNode("//Product/Name").InnerText;
decimal price = decimal.Parse(
    doc.SelectSingleNode("//Product/Price").InnerText);

The first block produces invalid XML the day a product called Nuts & Bolts arrives, and its price depends on the server's culture: a German server writes 9,99. The second block throws on the first file that omits an element.

The improved recipe

XDocument builds documents by construction, escapes every value, and reads with explicit casts that return null when something is missing.

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace ImproveCode.Serialization;

public sealed record Product(
    string Sku, string Name, decimal Price, DateTime? Discontinued);

public static class CatalogXml
{
    private static readonly XNamespace Ns = "urn:example:catalog:v1";

    public static XDocument Build(IEnumerable<Product> products) =>
        new(new XDeclaration("1.0", "utf-8", null),
            new XElement(Ns + "Catalog",
                new XAttribute("generated", DateTime.UtcNow),
                products.Select(p =>
                    new XElement(Ns + "Product",
                        new XAttribute("sku", p.Sku),
                        new XElement(Ns + "Name", p.Name),
                        new XElement(Ns + "Price", p.Price),
                        p.Discontinued is null
                            ? null
                            : new XElement(Ns + "Discontinued",
                                p.Discontinued.Value)))));

    public static List<Product> Parse(XDocument doc) =>
        doc.Root?.Elements(Ns + "Product")
            .Select(e => new Product(
                Sku: (string?)e.Attribute("sku") ?? "",
                Name: (string?)e.Element(Ns + "Name") ?? "",
                Price: (decimal?)e.Element(Ns + "Price") ?? 0m,
                Discontinued:
                    (DateTime?)e.Element(Ns + "Discontinued")))
            .ToList() ?? [];

    public static XDocument LoadSafely(string path)
    {
        var settings = new XmlReaderSettings
        {
            DtdProcessing = DtdProcessing.Prohibit,
            XmlResolver = null,
        };
        using XmlReader reader = XmlReader.Create(path, settings);
        return XDocument.Load(reader);
    }

    public static void RaisePrices(XDocument doc, decimal factor)
    {
        foreach (XElement price in doc.Descendants(Ns + "Price"))
        {
            decimal current = (decimal)price;
            price.Value = XmlConvert.ToString(
                Math.Round(current * factor, 2));
        }
    }
}

How it works

Functional construction mirrors the shape of the document. Each XElement constructor takes a name and any number of children: attributes, elements, sequences of elements, or null, which is skipped. That is why the conditional Discontinued element can return null inline.

Values are converted with XmlConvert, not with the current culture. A decimal becomes 9.99 everywhere, and a DateTime becomes an ISO 8601 string. Text is escaped automatically, so Nuts & Bolts becomes Nuts &amp; Bolts.

On the way back, the explicit conversion operators do the work. (string?)element returns null when the element is missing, and (decimal?)element and (DateTime?)element parse with XmlConvert rules. Combined with ?? you get a default instead of an exception, and the intent is visible on one line.

Namespaces are the part that trips people up. An element written as <Product xmlns="urn:example:catalog:v1"> is not found by Elements("Product"). You must ask for Ns + "Product". Attributes without a prefix are in no namespace, which is why sku is looked up without Ns.

Variations and pitfalls

  • Missing values versus bad values. (decimal?) returns null for a missing element but throws FormatException for <Price>abc</Price>. If partner data is dirty, use decimal.TryParse(e.Element(Ns + "Price")?.Value, NumberStyles.Number, CultureInfo.InvariantCulture, out var price).
  • XPath still works. using System.Xml.XPath; adds XPathSelectElements to XDocument. It is handy for paths copied from a partner's documentation. For anything you write yourself, LINQ queries are easier to read and refactor.
  • Saving. doc.Save(path) writes UTF-8 with a byte-order mark. For BOM-free output, save through an XmlWriter created with new UTF8Encoding(false), as in Recipe 12.3.
  • Large documents. XDocument holds the whole tree in memory, typically several times the file size. Past a few hundred megabytes, switch to the streaming approach in Recipe 12.6.