Working with XML in C#: Complete Beginner Guide
XML (Extensible Markup Language) is a widely used format for storing and exchanging structured data. Although JSON has become popular for web APIs, XML remains common in enterprise systems, configuration files, SOAP services, reporting tools, and data integrations.
C# provides several powerful ways to work with XML, allowing developers to create, read, update, search, and serialize XML documents efficiently.
In this tutorial, you'll learn how to work with XML in C# using XmlDocument, XDocument, LINQ to XML, and XML Serialization with practical examples and best practices.
- What is XML?
- Creating XML Documents
- Reading XML Files
- Writing XML Files
- XmlDocument
- XDocument
- LINQ to XML
- XML Serialization
- Common Mistakes
- Best Practices
What Is XML?
XML is a text-based format used to represent structured information. Data is organized using tags and nested elements.
<Product>
<Id>1</Id>
<Name>Laptop</Name>
<Price>999.99</Price>
</Product>
XML is human-readable and platform-independent, making it useful for exchanging data between systems.
Namespaces Required
Most XML operations require the following namespaces:
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
Creating an XML Document
The XDocument class provides a modern way to create XML documents.
var document = new XDocument(
new XElement("Product",
new XElement("Id", 1),
new XElement("Name", "Laptop"),
new XElement("Price", 999.99)
)
);
document.Save("product.xml");
This code creates an XML file and saves it to disk.
Reading XML Files
Load an existing XML document using XDocument.
var document =
XDocument.Load("product.xml");
Once loaded, you can access individual elements.
string name =
document.Root?
.Element("Name")?
.Value ?? "";
Writing XML Data
XML files can be updated and saved again.
document.Root?
.Element("Price")?
.SetValue(1099.99);
document.Save("product.xml");
Using XmlDocument
XmlDocument is an older XML API that is still widely used.
XmlDocument xml =
new XmlDocument();
xml.Load("product.xml");
Access nodes using SelectSingleNode.
var node =
xml.SelectSingleNode(
"//Name");
Console.WriteLine(node?.InnerText);
Using XDocument
XDocument is generally easier to use and more readable than XmlDocument.
var product =
document.Root;
Console.WriteLine(
product?.Element("Name")?.Value);
Working with Multiple Elements
XML often contains collections of records.
<Products>
<Product>
<Name>Laptop</Name>
</Product>
<Product>
<Name>Mouse</Name>
</Product>
</Products>
Retrieve all Product elements.
var products =
document.Descendants("Product");
LINQ to XML
LINQ makes querying XML documents simple and readable.
var productNames =
document.Descendants("Product")
.Select(p =>
p.Element("Name")?.Value);
LINQ allows filtering, sorting, and transforming XML data efficiently.
Filtering XML Data
var expensiveProducts =
document.Descendants("Product")
.Where(p =>
decimal.Parse(
p.Element("Price")!.Value)
> 500);
XML Serialization
Serialization converts C# objects into XML format.
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
XmlSerializer serializer =
new XmlSerializer(
typeof(Product));
Serialize an Object
using FileStream stream =
File.Create("product.xml");
serializer.Serialize(
stream,
product);
Deserialize XML
using FileStream stream =
File.OpenRead("product.xml");
Product? product =
serializer.Deserialize(stream)
as Product;
Deserialization converts XML back into a C# object.
Reading XML from a String
string xmlContent =
"<Product><Name>Laptop</Name></Product>";
var document =
XDocument.Parse(xmlContent);
Common Beginner Mistakes
- Ignoring null checks when reading elements.
- Using XmlDocument for simple scenarios.
- Hardcoding file paths.
- Forgetting exception handling.
- Using XML when JSON is more appropriate.
- Not validating XML structure.
Best Practices
- Prefer XDocument for new projects.
- Use LINQ to XML for queries.
- Validate XML before processing.
- Handle missing elements safely.
- Use serialization for object mapping.
- Keep XML structures consistent.
- Use proper exception handling.
Frequently Asked Questions
Is XML still used today?
Yes. XML remains widely used in enterprise applications, SOAP services, configuration files, and legacy systems.
Should I use XmlDocument or XDocument?
For most modern applications, XDocument is easier to use and generally recommended.
What is XML Serialization?
XML Serialization converts C# objects into XML and can also recreate objects from XML documents.
Can LINQ be used with XML?
Yes. LINQ to XML provides a powerful and readable way to query XML documents.
Related Tutorials
- Reading JSON in C#
- C# String Manipulation Guide
- File Handling in ASP.NET Core
- Using HttpClient in C#
- LINQ Cheat Sheet
- Working with Lists in C#
Conclusion
XML remains an important technology in many enterprise and integration scenarios. Understanding how to read, write, query, and serialize XML gives C# developers valuable skills for working with a wide range of systems.
By learning XDocument, LINQ to XML, XmlDocument, and XML Serialization, you'll be prepared to handle XML data efficiently in modern .NET applications.