Introduction

LINQ to XML is a powerful feature in C# that allows you to query and manipulate XML data using LINQ syntax. It provides a straightforward way to interact with XML documents, making it easier to read, create, and update XML data. In this post, we will explore the basics of LINQ to XML, including reading, querying, and modifying XML documents with practical examples.

Setting Up LINQ to XML in C#

To work with LINQ to XML in C#, you need to reference the System.Xml.Linq assembly. This assembly provides the necessary classes and methods to interact with XML documents.

Adding Reference:

  1. Visual Studio:
    • Right-click on your project in the Solution Explorer.
    • Select “Add” > “Reference”.
    • In the Reference Manager, check the box for System.Xml.Linq.
    • Click “OK”.
  2. .NET Core/.NET 5+:
    • The System.Xml.Linq assembly is included by default.

Creating and Loading XML Documents

Before you can query or manipulate XML data, you need to load the XML document. You can either load an existing XML file or create a new one.

Example: Creating an XML Document

using System;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        XElement books = new XElement("Books",
            new XElement("Book",
                new XElement("Title", "C# Programming"),
                new XElement("Author", "John Doe")
            ),
            new XElement("Book",
                new XElement("Title", "Learning LINQ"),
                new XElement("Author", "Jane Doe")
            )
        );

        Console.WriteLine(books);
    }
}

Explanation:

  • XElement: Represents an XML element. It can contain other elements, attributes, and text.
  • books: An XElement representing a collection of Book elements.

Output:

<Books>
  <Book>
    <Title>C# Programming</Title>
    <Author>John Doe</Author>
  </Book>
  <Book>
    <Title>Learning LINQ</Title>
    <Author>Jane Doe</Author>
  </Book>
</Books>

Loading an Existing XML Document

You can load an existing XML document using the XDocument.Load method.

Example: Loading an XML File

using System;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("books.xml");
        Console.WriteLine(doc);
    }
}

Explanation:

  • XDocument.Load: Loads the XML document from a file.
  • doc: An XDocument representing the loaded XML document.

Output (if books.xml contains the same structure as the previous example):

<Books>
  <Book>
    <Title>C# Programming</Title>
    <Author>John Doe</Author>
  </Book>
  <Book>
    <Title>Learning LINQ</Title>
    <Author>Jane Doe</Author>
  </Book>
</Books>

Querying XML Data with LINQ

Once you have an XML document, you can use LINQ to query its contents.

Example: Querying XML Data

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

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("books.xml");

        var query = from book in doc.Descendants("Book")
                    where (string)book.Element("Author") == "Jane Doe"
                    select book;

        Console.WriteLine("Books by Jane Doe:");
        foreach (var book in query)
        {
            Console.WriteLine(book.Element("Title").Value);
        }
    }
}

Explanation:

  • doc.Descendants(“Book”): Selects all Book elements in the document.
  • where (string)book.Element(“Author”) == “Jane Doe”: Filters books where the Author element’s value is “Jane Doe”.
  • select book: Selects the filtered Book elements.

Output:

Books by Jane Doe:
Learning LINQ

Modifying XML Data

You can also modify XML data using LINQ to XML.

Example: Adding a New Element

using System;
using System.Xml.Linq;

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("books.xml");

        XElement newBook = new XElement("Book",
            new XElement("Title", "Advanced C#"),
            new XElement("Author", "John Smith")
        );

        doc.Element("Books").Add(newBook);
        doc.Save("books.xml");
        Console.WriteLine("New book added.");
    }
}

Explanation:

  • newBook: An XElement representing the new book to be added.
  • doc.Element(“Books”).Add(newBook): Adds the new book to the Books element.
  • doc.Save(“books.xml”): Saves the modified document to the file.

Output:

New book added.

Removing an Element

You can remove an element from the XML document.

Example: Removing an Element

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

public class Program
{
    public static void Main()
    {
        XDocument doc = XDocument.Load("books.xml");

        var bookToRemove = doc.Descendants("Book")
                              .FirstOrDefault(b => (string)b.Element("Title") == "Advanced C#");

        if (bookToRemove != null)
        {
            bookToRemove.Remove();
            doc.Save("books.xml");
            Console.WriteLine("Book removed.");
        }
        else
        {
            Console.WriteLine("Book not found.");
        }
    }
}

Explanation:

  • bookToRemove: Finds the book with the title “Advanced C#” to remove.
  • bookToRemove.Remove(): Removes the selected book element.
  • doc.Save(“books.xml”): Saves the changes to the file.

Output:

Book removed.

Conclusion

LINQ to XML provides a powerful and flexible way to work with XML data in C#. It simplifies querying, creating, and modifying XML documents using familiar LINQ syntax. By mastering LINQ to XML, you can efficiently manage and manipulate XML data in your applications.

Similar Posts