Working with XML in C# (.NET): Complete Guide
XML (eXtensible Markup Language) remains one of the key formats for storing and transmitting structured data in the .NET ecosystem. C# provides several powerful libraries and approaches for working with XML, from the classic XmlDocument to the modern LINQ to XML. In this article, we will cover the main tools, their features, and provide practical examples for real-world tasks.
1. Main Libraries for Working with XML in .NET
The .NET platform provides developers with several APIs for processing XML:
- System.Xml (XmlDocument, XmlReader, XmlWriter) — the classic DOM approach (Document Object Model). Allows loading the entire XML document into memory and working with it as a tree of nodes.
- LINQ to XML (XDocument, XElement, XAttribute) — a modern, lighter, and more convenient API integrated with LINQ. Recommended for most new projects.
- XmlSerializer — for automatic serialization and deserialization of C# objects to and from XML.
- XPath (SelectSingleNode, SelectNodes) — a query language for navigating an XML document. Supported in both
XmlDocumentandXDocument(via extensions).
2. LINQ to XML: Modern Approach
The System.Xml.Linq library (LINQ to XML) is the preferred choice for working with XML in C#. It offers clean syntax, easy loading, and support for LINQ queries.
Creating an XML Document
using System.Xml.Linq;
XDocument doc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XElement("books", new XElement("book", new XAttribute("id", "1"), new XElement("title", "War and Peace"), new XElement("author", "Leo Tolstoy"), new XElement("price", 599.99m) ), new XElement("book", new XAttribute("id", "2"), new XElement("title", "Crime and Punishment"), new XElement("author", "Fyodor Dostoevsky"), new XElement("price", 450.00m) ) ));
doc.Save("books.xml");Loading and Reading XML
XDocument loadedDoc = XDocument.Load("books.xml");
// Get all booksvar allBooks = loadedDoc.Descendants("book");
foreach (var book in allBooks){ string id = book.Attribute("id")?.Value; string title = book.Element("title")?.Value; string author = book.Element("author")?.Value; Console.WriteLine($"Book #{id}: {title} — {author}");}LINQ Queries
// Select books more expensive than 500 rublesvar expensiveBooks = from book in loadedDoc.Descendants("book") where (decimal)book.Element("price") > 500 select new { Title = (string)book.Element("title"), Price = (decimal)book.Element("price") };
foreach (var b in expensiveBooks){ Console.WriteLine($"{b.Title}: {b.Price} rub.");}3. Classic XmlDocument
If you are working with legacy code or require full control over the DOM, use XmlDocument from the System.Xml namespace.
Loading and Navigation
using System.Xml;
XmlDocument xmlDoc = new XmlDocument();xmlDoc.Load("books.xml");
XmlNode root = xmlDoc.DocumentElement;XmlNodeList bookNodes = root.SelectNodes("book");
foreach (XmlNode node in bookNodes){ XmlNode titleNode = node.SelectSingleNode("title"); if (titleNode != null) { Console.WriteLine(titleNode.InnerText); }}Adding a New Node
XmlNode newBook = xmlDoc.Cre Also in library
GraphQL in C++: cppgraphqlgen Library for Creating APIs
Working with Images in Rust: Overview of image, fast_image_resize, and other Libraries
Retrofit for Java: Complete Guide with Examples
HTTP Client for JavaScript (Node.js): Top Libraries for Working with API
Dokka for Kotlin: Complete Guide with Examples