Working with XML in C#

XML (Extensible Markup Language) is a widely used markup language for storing and transporting structured data. Its main advantage is the flexibility in data representation and the ability to be read by different systems and platforms. In software development, XML is often used for data exchange between systems and configuration persistence.

Basic Concepts of XML

XML uses tags to define data structure, allowing the creation of a hierarchical format. An XML file can be represented by a series of elements (tags) with attributes and values:

				
					<books>
  <book>
    <title>The Little Prince</title>
    <author>Antoine de Saint-Exupéry</author>
    <year>1943</year>
  </book>
  <book>
    <title>1984</title>
    <author>George Orwell</author>
    <year>1949</year>
  </book>
</books>
				
			

The example above shows an XML structure containing a <books> tag that holds multiple <book> elements, each with child elements such as <title>, <author>, and <year>. Analogous to C#, it would be a collection of “books” containing multiple “book” objects, each having properties “title”, “author”, and “year”.

Serializing and Deserializing Objects with XmlSerializer

In C#, the XmlSerializer class is used to convert objects to XML and vice versa. Let’s see how to serialize and deserialize objects.

Serialization

Serialization is the process of converting a C# object into XML format. For this, we can create a C# class:

				
					public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Year { get; set; }
}
				
			

To serialize a Book object to XML, we use the following code:

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

var book = new Book
{
    Title = "The Little Prince",
    Author = "Antoine de Saint-Exupéry",
    Year = 1943
};

XmlSerializer serializer = new XmlSerializer(typeof(Book));
using (StringWriter writer = new StringWriter())
{
    serializer.Serialize(writer, book);
    string xml = writer.ToString();
    Console.WriteLine(xml);
}
				
			

The output will be:

				
					<Book>
  <Title>The Little Prince</Title>
  <Author>Antoine de Saint-Exupéry</Author>
  <Year>1943</Year>
</Book>
				
			

Deserialization

Deserialization is the process of converting XML back into a C# object. We use the Deserialize method of the XmlSerializer class.

				
					string xml = @"<Book>
                  <Title>The Little Prince</Title>
                  <Author>Antoine de Saint-Exupéry</Author>
                  <Year>1943</Year>
               </Book>";

XmlSerializer serializer = new XmlSerializer(typeof(Book));
using (StringReader reader = new StringReader(xml))
{
    Book book = (Book)serializer.Deserialize(reader);
    Console.WriteLine($"Title: {book.Title}, Author: {book.Author}, Year: {book.Year}");
}
				
			

The output will be:

Title: The Little Prince, Author: Antoine de Saint-Exupéry, Year: 1943

Manipulating XML Files with XDocument

Besides serializing and deserializing objects, we can also directly manipulate XML files using XDocument, part of LINQ to XML, providing a modern and fluent way to work with XML.

				
					var book = new Book
{
    Title = "The Little Prince",
    Author = "Antoine de Saint-Exupéry",
    Year = 1943
};

XDocument doc = new XDocument(
    new XElement("Books",
        new XElement(nameof(Book),
            new XElement(nameof(Book.Title), book.Title),
            new XElement(nameof(Book.Author), book.Author),
            new XElement(nameof(Book.Year), book.Year)
        )
    )
);

doc.Save(@"D:\\book.xml");
				
			

Here, after creating a Book object, an XML document is built using XDocument and XElement. The nameof operator ensures that the XML element names match the class property names exactly.

Finally, the Save method stores the generated XML to a specified file path.

Reading and Editing an XML Document

Now let’s see how it is possible to read and edit an XML file.

Reading

				
					XDocument doc = XDocument.Load(@"D:\\book.xml");

foreach (var book in doc.Descendants("Book"))
{
    Console.WriteLine($"Title: {book.Element("Title").Value}, Author: {book.Element("Author").Value}, Year: {book.Element("Year").Value}");
}
				
			

To read an XML file, we can use the Load method of the XDocument class. When we provide the XML file path as a parameter, the method loads the XML file into memory, allowing us to manipulate it.

After loading the document, we can use the Descendants method to access all elements of a specific type within the XML. In our example, we are looking for all <Book> elements, which represent the book records in the XML.

Inside the foreach loop, we iterate over each <Book> element. To access the data of each book, we use the Element method, passing the name of the element we want to access (for example, “title” or “author”). The Element method returns an XElement, and the Value property is used to retrieve the value contained in that element.

Editing

				
					doc.Descendants("Book").First().Element("Year").Value = "1945";
doc.Save(@"D:\\book.xml");
				
			

To edit the XML, we use the Descendants method to locate all <Book> elements.

Next, the First() method is used to access the first element in the returned collection. First() is useful when you want to modify only the first element that matches the criteria (in this case, the first <Book>). If you wanted to access a specific element, you could use methods like Where to filter elements based on their properties.

The Element("Year") method is used to access the <Year> subelement, and by setting Value = "1945", we change the year from “1943” to “1945.”

Finally, the Save method saves the changes to the specified XML file.

Conclusion

Working with XML in C# on .NET offers an easy and flexible approach for handling structured data. Tools like XmlSerializer and XDocument provide efficient solutions for both serialization and editing of XML documents, making it intuitive and straightforward to work with data while ensuring integration with complex systems remains reliable, scalable, and maintainable.