XML in C# Example
Working with XML in C# is made simpler with classes from the System.Xml namespace. These classes allow you to read, write, manipulate, and validate XML data. This article provides an example of how to read and write XML in C#.
Reading XML in C#
Example: Loading and Reading XML Document
To read XML data from a file or a string, use the XmlDocument class.
using System;
using System.Xml;
public class XmlReadExample
{
public static void Main()
{
// Sample XML data
string xmlData = @"
<library>
<book>
<title>The Catcher in the Rye</title>
<author>J.D. Salinger</author>
<year>1951</year>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
</book>
</library>";
// Load the XML data into an XmlDocument object
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlData);
// Access specific elements 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}");
}
}
}
Writing XML in C#
Example: Creating and Saving an XML Document
To write an XML document, use the XmlWriter or XmlDocument class.
using System;
using System.Xml;
public class XmlWriteExample
{
public static void Main()
{
// Create a new XmlDocument object
XmlDocument doc = new XmlDocument();
// Create the root element
XmlElement libraryElement = doc.CreateElement("library");
doc.AppendChild(libraryElement);
// Add a book element
XmlElement bookElement = doc.CreateElement("book");
libraryElement.AppendChild(bookElement);
// Add child elements to the book element
XmlElement titleElement = doc.CreateElement("title");
titleElement.InnerText = "1984";
bookElement.AppendChild(titleElement);
XmlElement authorElement = doc.CreateElement("author");
authorElement.InnerText = "George Orwell";
bookElement.AppendChild(authorElement);
XmlElement yearElement = doc.CreateElement("year");
yearElement.InnerText = "1949";
bookElement.AppendChild(yearElement);
// Save the document to a file
string filePath = "library.xml";
doc.Save(filePath);
Console.WriteLine($"XML document saved to {filePath}");
}
}
Conclusion
C# provides comprehensive tools for handling XML documents through the System.Xml namespace. By using the XmlDocument class or XmlWriter, you can efficiently read and write XML data to manage complex hierarchical data structures.