How to parse XML with XElement in LINQ

By FoxLearn 3/1/2025 2:39:58 AM   35
The XElement class (from the LINQ-to-XML API) is a powerful tool for parsing and manipulating XML in memory. It allows you to search for XML elements, retrieve attributes, and modify values.

Parse an XML String with XElement

To parse an XML string, you can use the XElement.Parse() method, which returns an XElement object.

For example, parser an XML string and extracting values:

using System.Xml.Linq;

var xmlString =
"""
<Library>
    <Book>
        <Title>To Kill a Mockingbird</Title>
        <Author>Harper Lee</Author>
        <Year>1960</Year>
    </Book>
</Library>
""";

var library = XElement.Parse(xmlString);

var title = library.Element("Book")?.Element("Title")?.Value;
var author = library.Element("Book")?.Element("Author")?.Value;
var year = library.Element("Book")?.Element("Year")?.Value;

Console.WriteLine($"{title} by {author} was published in {year}");

Output:

To Kill a Mockingbird by Harper Lee was published in 1960

Parse an XML File with XElement

To parse an XML file, use XElement.Load() and specify the file path. The method returns an XElement object.

For example, let’s assume you have an XML file named books.xml with the following content:

<Library>
    <Book genre="fiction">
        <Title>1984</Title>
        <Author>George Orwell</Author>
        <Year>1949</Year>
    </Book>
    <Book genre="non-fiction">
        <Title>Sapiens</Title>
        <Author>Yuval Noah Harari</Author>
        <Year>2011</Year>
    </Book>
    <Book genre="fiction">
        <Title>Brave New World</Title>
        <Author>Aldous Huxley</Author>
        <Year>1932</Year>
    </Book>
</Library>

You can use the following code to parse this file and count how many books are classified as “fiction”:

using System.Linq;
using System.Xml.Linq;

var booksXml = XElement.Load("books.xml");

// How many fiction books?
var fictionCount = booksXml.Descendants("Book")
    .Count(b => b.Attribute("genre")?.Value == "fiction");

Console.WriteLine($"There are {fictionCount} fiction books.");

Output:

There are 2 fiction books.

Parsing an XML Document with XDocument

When working with an XML document that includes additional features, such as document type declarations and comments, it's better to use the XDocument class. Unlike XElement, XDocument preserves these features.

For instance, let’s consider an XML file with the following content, which includes an XML declaration and comments:

<?xml version="1.0" encoding="utf-8"?>
<Library>
    <!-- List of classic books -->
    <Book id="101" available="true">Pride and Prejudice</Book>
    <Book id="102" available="false">Moby Dick</Book>
    <Book id="103" available="true">The Great Gatsby</Book>
</Library>

You can use XDocument to parse this file, modify some values, and save the changes:

using System.Xml.Linq;

var booksXMLDoc = XDocument.Load("books.xml");

// Set all books' "available" attribute to true
foreach (var book in booksXMLDoc.Descendants("Book"))
{
    book.SetAttributeValue("available", "true");
}

// Save the modified document
booksXMLDoc.Save("books.xml");

This will result in the following XML being saved, with the document features preserved:

<?xml version="1.0" encoding="utf-8"?>
<Library>
    <!-- List of classic books -->
    <Book id="101" available="true">Pride and Prejudice</Book>
    <Book id="102" available="true">Moby Dick</Book>
    <Book id="103" available="true">The Great Gatsby</Book>
</Library>

The XElement class is a convenient and efficient way to work with XML in C#, particularly for parsing and modifying simple XML data. However, when working with more complex XML documents that include features like comments or document declarations, XDocument is the better choice.