Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

LINQ to XML Tutorial

Introduction

LINQ to XML provides an in-memory XML programming interface that leverages the power of LINQ (Language Integrated Query). It allows developers to query and manipulate XML data easily using C#. In this tutorial, we will cover the basics of LINQ to XML, including creating, querying, and modifying XML documents.

Creating XML Documents

To create an XML document using LINQ to XML, we use the XDocument and XElement classes. Here's a simple example:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        XDocument doc = new XDocument(
            new XElement("Books",
                new XElement("Book",
                    new XElement("Title", "The Great Gatsby"),
                    new XElement("Author", "F. Scott Fitzgerald")
                ),
                new XElement("Book",
                    new XElement("Title", "1984"),
                    new XElement("Author", "George Orwell")
                )
            )
        );

        Console.WriteLine(doc);
    }
}

The above code creates an XML document with a root element <Books>, containing two <Book> elements.

<Books>
  <Book>
    <Title>The Great Gatsby</Title>
    <Author>F. Scott Fitzgerald</Author>
  </Book>
  <Book>
    <Title>1984</Title>
    <Author>George Orwell</Author>
  </Book>
</Books>

Querying XML Documents

LINQ to XML enables querying XML data using LINQ queries. Here's how you can select all book titles from the XML document:

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

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

        var titles = from book in doc.Descendants("Book")
                     select book.Element("Title").Value;

        foreach (var title in titles)
        {
            Console.WriteLine(title);
        }
    }
}

This code loads an XML document from a file and uses a LINQ query to select all book titles.

The Great Gatsby
1984

Modifying XML Documents

With LINQ to XML, you can also modify existing XML documents. Here's an example of adding a new book to the XML document:

using System;
using System.Xml.Linq;

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

        XElement newBook = new XElement("Book",
            new XElement("Title", "To Kill a Mockingbird"),
            new XElement("Author", "Harper Lee")
        );

        doc.Root.Add(newBook);
        doc.Save("books.xml");

        Console.WriteLine(doc);
    }
}

This code adds a new <Book> element to the existing XML document and saves it back to the file.

<Books>
  <Book>
    <Title>The Great Gatsby</Title>
    <Author>F. Scott Fitzgerald</Author>
  </Book>
  <Book>
    <Title>1984</Title>
    <Author>George Orwell</Author>
  </Book>
  <Book>
    <Title>To Kill a Mockingbird</Title>
    <Author>Harper Lee</Author>
  </Book>
</Books>

Deleting Elements

You can also delete elements from an XML document. Here's an example of deleting a book by title:

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

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

        var bookToDelete = doc.Descendants("Book")
                              .FirstOrDefault(b => b.Element("Title").Value == "1984");

        if (bookToDelete != null)
        {
            bookToDelete.Remove();
            doc.Save("books.xml");
        }

        Console.WriteLine(doc);
    }
}

This code finds and removes the <Book> element with the title "1984" and saves the modified document.

<Books>
  <Book>
    <Title>The Great Gatsby</Title>
    <Author>F. Scott Fitzgerald</Author>
  </Book>
  <Book>
    <Title>To Kill a Mockingbird</Title>
    <Author>Harper Lee</Author>
  </Book>
</Books>

Updating Elements

To update elements in an XML document, you can modify the values of existing elements. Here's an example:

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

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

        var bookToUpdate = doc.Descendants("Book")
                              .FirstOrDefault(b => b.Element("Title").Value == "The Great Gatsby");

        if (bookToUpdate != null)
        {
            bookToUpdate.Element("Author").Value = "Anonymous";
            doc.Save("books.xml");
        }

        Console.WriteLine(doc);
    }
}

This code updates the author of the book titled "The Great Gatsby" to "Anonymous" and saves the changes.

<Books>
  <Book>
    <Title>The Great Gatsby</Title>
    <Author>Anonymous</Author>
  </Book>
  <Book>
    <Title>To Kill a Mockingbird</Title>
    <Author>Harper Lee</Author>
  </Book>
</Books>

Conclusion

LINQ to XML is a powerful feature in C# that simplifies the process of working with XML data. By leveraging the power of LINQ, developers can easily create, query, modify, and delete XML elements in a clean and readable manner. With the basics covered in this tutorial, you should be ready to start using LINQ to XML in your projects.