Working with XML in C# (.NET): A Complete Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with XML in C# (.NET): A Complete Guide



XML (Extensible Markup Language) remains one of the key formats for storing and transmitting structured data in the .NET ecosystem. In C#, several powerful tools are available for working with XML: from the classic XmlDocument to the modern XDocument from LINQ to XML and advanced serialization via XmlSerializer. In this article, we will cover all the main approaches with practical examples.



1. Classic Approach: XmlDocument



System.Xml.XmlDocument is a DOM model (Document Object Model) that loads the entire XML document into memory as a tree of nodes. This approach has been familiar to developers since .NET Framework 1.0.



Loading and Reading XML



using System.Xml;

XmlDocument doc = new XmlDocument();doc.Load("books.xml");

// Get the root elementXmlElement root = doc.DocumentElement;

// Traverse all child nodesforeach (XmlNode node in root.ChildNodes){ if (node.Name == "book") { string title = node["title"]?.InnerText; string author = node["author"]?.InnerText; Console.WriteLine($"Book: {title}, Author: {author}"); }}


Creating and Writing XML



XmlDocument newDoc = new XmlDocument();XmlElement rootElem = newDoc.CreateElement("library");newDoc.AppendChild(rootElem);

XmlElement book = newDoc.CreateElement("book");rootElem.AppendChild(book);

XmlElement title = newDoc.CreateElement("title");title.InnerText = "The Master and Margarita";book.AppendChild(title);

newDoc.Save("library.xml");


Pros: Simplicity, XPath support, full control over DOM.
Cons: High memory consumption, no LINQ support.



2. Modern Approach: LINQ to XML (XDocument)



Starting with .NET 3.5, it is recommended to use the System.Xml.Linq namespace. The XDocument, XElement, and XAttribute classes provide a lighter and more functional API with full LINQ integration.



Reading XML with XDocument



using System.Xml.Linq;

XDocument xdoc = XDocument.Load("books.xml");

var books = xdoc.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.Author} ({book.Year})");}


Creating XML with XElement



XDocument xdoc = new XDocument(    new XElement("library",        new XElement("book",            new XElement("title", "Crime and Punishment"),            new XElement("author", "F.M. Dostoevsky"),            new XAttribute("id", "1")        )    ));

xdoc.Save("library2.xml");


Pros: Concise syntax, LINQ support, lower memory consumption.
Cons: May be unfamiliar to developers accustomed to DOM.



3. Object Serialization to XML: XmlSerializer



If you have C# classes, you can automatically convert them to XML and back using System.Xml.Serialization.XmlSerializer.



Example Class for Serialization



[Serializable]public class Book{    [XmlAttribute("id")]    public int Id { get; set; }

[XmlElement("title")] public string Title { get; set; }

[XmlElement("author")] public string Author { get; set; }

[XmlIgnore] public string InternalNote { get; set; }}


Serialization (Object → XML)



using System.Xml.Serialization;using System.IO;

Book book = new Book { Id = 1, Title = "War and Peace", Author = "L.N. Tolstoy" };

XmlSeria

Recommendations