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.
XDocument doc = XDocument.Parse("<items><item id='1'>pen</item></items>"); string name = doc.Root!.Element("item")!.Value; // "pen"
Try it
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.
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
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 returnnullfor 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"; usens + "server". A frequent bug is queries returning nothing because the file has a default namespace. ToString()formats,Valueflattens.element.ToString()returns indented XML,ToString(SaveOptions.DisableFormatting)returns it compact, andValuereturns text only.- The tree is mutable and live. Removing nodes while iterating a lazy query is a classic mistake. Call
.ToList()first, or useRemove()on the query result (the extension method handles the copying). - Functional construction. Passing an
IEnumerableas content adds every item, sonew 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.PreserveWhitespacekeeps it). - Streaming large files.
XDocumentloads everything into memory. For multi-hundred-megabyte files useXmlReaderand callXNode.ReadFromfor one element at a time. XDocumentvs.XElement. UseXElement.Parse/Loadwhen you do not need the XML declaration, comments before the root, or a document type; useXDocumentwhen you do.- Safety.
XDocument.Loadprohibits DTD processing by default, which protects against entity-expansion attacks. Only relax that with explicitXmlReaderSettingsfor trusted input. - Alternatives.
XmlSerializermaps XML directly to classes; the olderXmlDocumentDOM still works but is more verbose.