Working with XML in C# (.NET): From Basics to Advanced Techniques
XML (eXtensible Markup Language) remains one of the key formats for storing and transmitting structured data in the .NET ecosystem. Whether you are creating configuration files, exchanging data with web services, or processing documents, the built-in C# tools provide flexible and efficient instruments for working with XML. In this article, we will cover three main approaches: the classic XmlDocument, the modern XDocument (LINQ to XML), and the streaming XmlReader/XmlWriter.
1. Classic XmlDocument (DOM Model)
The System.Xml.XmlDocument class implements the DOM (Document Object Model) — it loads the entire XML document into memory as a tree of nodes. This is convenient for small and medium-sized documents when frequent navigation and modification are required.
Loading and Reading XML
using System.Xml;
XmlDocument doc = new XmlDocument();doc.Load("books.xml"); // loading from file
// Getting the root elementXmlElement root = doc.DocumentElement;
// Selecting all book elementsXmlNodeList books = root.SelectNodes("//book");foreach (XmlNode book in books){ string title = book["title"].InnerText; string author = book["author"].InnerText; Console.WriteLine($"{title} — {author}");}Creating and Saving XML
XmlDocument doc = new XmlDocument();XmlElement root = doc.CreateElement("library");doc.AppendChild(root);
XmlElement book = doc.CreateElement("book");book.SetAttribute("id", "1");
XmlElement title = doc.CreateElement("title");title.InnerText = "War and Peace";book.AppendChild(title);
root.AppendChild(book);doc.Save("library.xml");2. Modern LINQ to XML (XDocument)
The System.Xml.Linq namespace offers a more concise and functional API. XDocument and XElement allow you to write code in a LINQ style, which is especially convenient for queries and transformations.
Parsing with XDocument
using System.Xml.Linq;
XDocument doc = XDocument.Load("books.xml");
var books = doc.Descendants("book") .Select(b => new { Title = b.Element("title")?.Value, Author = b.Element("author")?.Value, Year = (int)b.Element("year") });
foreach (var book in books){ Console.WriteLine($"{book.Title} ({book.Year})");}Creating XML with Constructors
XDocument doc = new XDocument( new XElement("library", new XElement("book", new XAttribute("id", "1"), new XElement("title", "Crime and Punishment"), new XElement("author", "F.M. Dostoevsky") ) ));doc.Save("library.xml");Advantages of XDocument:
- Support for LINQ queries for filtering and projecting data.
- More readable syntax for creating elements using nested constructors.
- Automatic namespace handling via
XNamespace.
3. Streaming Processing: XmlReader and XmlWriter
For working with large XML files (hundreds of megabytes or gigabytes), using XmlDocument or XDocument can lead to memory overflow. In such cases, the streaming classes XmlReader and XmlWriter are used, which process data sequentially without loading the entire document.
Reading with XmlReader
using (XmlReader reader = XmlReader.Create("large.xml")){ while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name == "record") { string id = reader.Get