LinQ to XML Data in C#

By FoxLearn 12/25/2024 9:34:54 AM   100
In this tutorial, We will cover fundamental operations such as retrieving, inserting, updating, and deleting data in XML files using Linq in C#.

For this tutorial, we will use a simple XML structure:

<?xml version="1.0" encoding="utf-8" ?>
<Books>
  <Book ID="1">
    <Title>Book One</Title>
    <Author>Author One</Author>
  </Book>
  <Book ID="2">
    <Title>Book Two</Title>
    <Author>Author Two</Author>
  </Book>
  <Book ID="3">
    <Title>Book Three</Title>
    <Author>Author Three</Author>
  </Book>
</Books>

In this XML, the root element is <Books>, which contains several <Book> elements. Each <Book> has an ID attribute and two child elements: <Title> and <Author>.

1. Retrieving Data with Linq to XML

We can easily retrieve data from an XML file using Linq. Below is a sample code that retrieves information from the XML file and displays it:

private string path = "BooksData.xml";

private void GetXMLData()
{
    try
    {
        XDocument xmlDoc = XDocument.Load(path);
        var books = from book in xmlDoc.Descendants("Book")
                    select new
                    {
                        ID = Convert.ToInt32(book.Attribute("ID").Value),
                        Title = book.Element("Title").Value,
                        Author = book.Element("Author").Value
                    };

        foreach (var book in books)
        {
            Console.WriteLine($"ID: {book.ID}, Title: {book.Title}, Author: {book.Author}");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

In this example:

  • We load the XML file into an XDocument object.
  • We query the <Book> elements using Descendants("Book").
  • We select the ID, Title, and Author using Linq and store them in an anonymous object.
  • We print out each book's information.

2. Inserting Data Using Linq to XML

To insert new data into an XML file, you can create a new XElement object, append it to the XML document, and save the changes.

private void InsertXMLData(string title, string author)
{
    try
    {
        XDocument xmlDoc = XDocument.Load(path);
        
        XElement newBook = new XElement("Book",
            new XAttribute("ID", 4),
            new XElement("Title", title),
            new XElement("Author", author)
        );

        xmlDoc.Element("Books").Add(newBook);
        xmlDoc.Save(path);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

In this example:

  • Loads the XML document.
  • Creates a new XElement for a book with a title, author, and a unique ID.
  • Adds this new book to the <Books> element and saves the XML file.

3. Updating Data Using Linq to XML

To update existing data, you first retrieve the relevant XElement, modify its content, and then save the changes.

private void UpdateXMLData(int id, string newTitle, string newAuthor)
{
    try
    {
        XDocument xmlDoc = XDocument.Load(path);
        XElement bookToUpdate = xmlDoc.Descendants("Book")
            .FirstOrDefault(b => (int)b.Attribute("ID") == id);

        if (bookToUpdate != null)
        {
            bookToUpdate.Element("Title").Value = newTitle;
            bookToUpdate.Element("Author").Value = newAuthor;
            xmlDoc.Save(path);
        }
        else
        {
            Console.WriteLine("Book not found.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

In this example:

  • We find the <Book> element with the specified ID.
  • We update its Title and Author elements with new values.
  • We save the updated XML back to the file.

4. Deleting Data Using Linq to XML

To delete a record from the XML, simply retrieve the matching element and call the Remove() method to remove it from the document.

private void DeleteXMLData(int id)
{
    try
    {
        XDocument xmlDoc = XDocument.Load(path);
        XElement bookToDelete = xmlDoc.Descendants("Book")
            .FirstOrDefault(b => (int)b.Attribute("ID") == id);

        if (bookToDelete != null)
        {
            bookToDelete.Remove();
            xmlDoc.Save(path);
        }
        else
        {
            Console.WriteLine("Book not found.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

In this example:

  • Finds the <Book> element with the given ID.
  • Removes the element from the document.
  • Saves the changes to the XML file.

In this tutorial, we’ve covered how to perform basic operations such as retrieving, inserting, updating, and deleting data in XML files using Linq to XML in C#.