How to Read and Write XML File in C#
In C#, working with XML files is convenient using the classes available in the System.Xml namespace. Whether you're handling configuration files, data exchange, or custom data storage, XML provides a versatile way to manage structured data. This article explains how to read and write XML files in C# using practical examples.
Reading an XML File
Example: Reading XML with XmlDocument
The XmlDocument class provides a way to load, navigate, and extract data from XML files.
using System;
using System.Xml;
public class XmlReadExample
{
public static void Main()
{
// Path to the XML file
string filePath = "library.xml";
// Load the XML file into an XmlDocument
XmlDocument doc = new XmlDocument();
doc.Load(filePath);
// Access nodes using XPath
XmlNodeList bookNodes = doc.SelectNodes("//book");
Console.WriteLine("Books in the Library:");
foreach (XmlNode book in bookNodes)
{
string title = book["title"]?.InnerText;
string author = book["author"]?.InnerText;
string year = book["year"]?.InnerText;
Console.WriteLine($"Title: {title}, Author: {author}, Year: {year}");
}
}
}
Tips for Reading XML Files
- XPath Expressions: Use XPath expressions like //book to navigate through elements efficiently.
- Exception Handling: Use try-catch blocks to handle potential file errors gracefully.
Writing to an XML File
Example: Writing XML with XmlWriter
To write XML data to a file, the XmlWriter class provides a flexible way to generate XML content.
using System;
using System.Xml;
public class XmlWriteExample
{
public static void Main()
{
// Path where the XML file will be created
string filePath = "library.xml";
// Set up XmlWriter settings
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true,
NewLineOnAttributes = false
};
// Create the XmlWriter object
using (XmlWriter writer = XmlWriter.Create(filePath, settings))
{
// Start the document
writer.WriteStartDocument();
writer.WriteStartElement("library");
// Write a book element
writer.WriteStartElement("book");
writer.WriteElementString("title", "To Kill a Mockingbird");
writer.WriteElementString("author", "Harper Lee");
writer.WriteElementString("year", "1960");
writer.WriteEndElement(); // book
writer.WriteEndElement(); // library
writer.WriteEndDocument(); // End the document
}
Console.WriteLine($"XML document saved to {filePath}");
}
}
Tips for Writing XML Files
- XmlWriterSettings: Customize indentation and new-line behavior using XmlWriterSettings.
- Well-Formed XML: Ensure that your XML is well-formed by correctly closing all tags.
Conclusion
In C#, reading and writing XML files is straightforward using the System.Xml namespace. By leveraging the XmlDocument and XmlWriter classes, you can handle structured data efficiently for any application.