Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

XDocument and LINQ to XML

Reference for XDocument, XElement and XAttribute in C#: parse, query with LINQ, build, modify and save XML, plus namespaces and XPath.

LINQ to XML (the System.Xml.Linq namespace) is the modern way to work with XML in C#. An XDocument represents a whole document; XElement is an element, XAttribute an attribute, and XNamespace and XName handle namespaces. Everything is an object tree you can build, query with LINQ, modify and write back.

You can create XML with functional construction: the XElement constructor takes the name followed by any number of attributes, child elements and text, so the code looks like the XML it produces. You read XML with XDocument.Parse(string) or XDocument.Load(path), then use Element, Elements, Descendants, Attribute and LINQ operators to pull data out.

C#
XDocument doc = XDocument.Parse("<items><item id='1'>pen</item></items>");
string name = doc.Root!.Element("item")!.Value;   // "pen"

Try it

C# Build, query and print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Modify, namespaces and saving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public static XDocument XDocument.Parse(string text, LoadOptions options = LoadOptions.None);
public static XDocument XDocument.Load(string uri);
public static XDocument XDocument.Load(Stream stream);
public void Save(string fileName);
public void Save(TextWriter textWriter, SaveOptions options);

public XElement(XName name, params object?[] content);
public XAttribute(XName name, object value);

public XElement? Element(XName name);
public IEnumerable<XElement> Elements(XName? name = null);
public IEnumerable<XElement> Descendants(XName? name = null);
public XAttribute? Attribute(XName name);
public void Add(object? content);
public void SetValue(object value);
public void SetAttributeValue(XName name, object? value);
public void Remove();
Name Description
Element(name) The first child element with that name, or null.
Elements(name) Direct child elements (all, or only matching).
Descendants(name) All nested elements at any depth, in document order.
Attribute(name) The attribute, or null.
Value The concatenated text of the element and its children.
Explicit casts (int)element, (string)element, (decimal?)attribute, (DateTime)element, (bool)element and so on parse the value.
LoadOptions PreserveWhitespace, SetLineInfo (enables IXmlLineInfo) and SetBaseUri.
SaveOptions DisableFormatting, OmitDuplicateNamespaces.

Returns: Element and Attribute return null when nothing matches; the sequences are lazy.

Errors: XmlException for malformed input, FormatException for failed casts, InvalidCastException for unsupported casts, ArgumentException for invalid names, and NullReferenceException when you use .Value on a missing node.

Usage notes

  • Cast instead of .Value. (string?)el, (int?)el.Attribute("x") and friends return null for a missing node instead of throwing, which makes optional data painless.
  • Namespaces are part of the name. An element in xmlns="urn:..." is not found by a plain "server"; use ns + "server". A frequent bug is queries returning nothing because the file has a default namespace.
  • ToString() formats, Value flattens. element.ToString() returns indented XML, ToString(SaveOptions.DisableFormatting) returns it compact, and Value returns text only.
  • The tree is mutable and live. Removing nodes while iterating a lazy query is a classic mistake. Call .ToList() first, or use Remove() on the query result (the extension method handles the copying).
  • Functional construction. Passing an IEnumerable as content adds every item, so new XElement("list", items.Select(i => new XElement("i", i))) builds a whole collection in one expression.
  • Whitespace. By default, whitespace-only text between elements is dropped on parse (LoadOptions.PreserveWhitespace keeps it).
  • Streaming large files. XDocument loads everything into memory. For multi-hundred-megabyte files use XmlReader and call XNode.ReadFrom for one element at a time.
  • XDocument vs. XElement. Use XElement.Parse/Load when you do not need the XML declaration, comments before the root, or a document type; use XDocument when you do.
  • Safety. XDocument.Load prohibits DTD processing by default, which protects against entity-expansion attacks. Only relax that with explicit XmlReaderSettings for trusted input.
  • Alternatives. XmlSerializer maps XML directly to classes; the older XmlDocument DOM still works but is more verbose.