How to Safely Update XML Data Using LINQ and DataSet in C#

← Prev

XML is still widely used in many .NET applications for configuration files, data exchange, legacy integrations, and structured data storage. Whether you are maintaining an existing application or building a new C# solution, updating XML data safely is an important skill.

C# provides several ways to work with XML, but two commonly used approaches are LINQ to XML and DataSet.

LINQ to XML offers a simple and flexible way to query and modify XML elements, attributes, and values. On the other hand, the DataSet class provides a convenient way to work with XML data in a tabular format.

In this article, we will explore how to safely update XML data using LINQ and DataSet in C#, including practical examples, validation techniques, exception handling, and best practices.

<Employees> <Employee> <Name>John <Salary>50000 </Employee> </Employees> C# .NET var doc = XDocument .Load(file); element.Value = "50000"; SAFE XML UPDATES IN C# LINQ TO XML • DATASET • VALIDATION

Understanding XML Data Manipulation in C#

Before updating XML data, it is important to understand its structure.

Consider the following XML file named Employees.xml:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
    <Employee Id="1">
        <Name>John</Name>
        <Department>IT</Department>
        <Salary>45000</Salary>
    </Employee>
    <Employee Id="2">
        <Name>David</Name>
        <Department>HR</Department>
        <Salary>40000</Salary>
    </Employee>
</Employees>

Suppose we want to update John's salary from 45000 to 50000.

We can accomplish this using either LINQ to XML or DataSet.

Updating XML Data Using LINQ to XML

LINQ to XML is one of the easiest ways to modify XML documents in C#.

It provides useful classes such as:

First, import the required namespaces:

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

Update an XML Element Using LINQ

The following example updates an employee's salary based on their ID.

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

class Program
{
    static void Main()
    {
        string filePath = "Employees.xml";

        XDocument doc = XDocument.Load(filePath);

        XElement employee = doc
            .Descendants("Employee")
            .FirstOrDefault(e =>
                (string)e.Attribute("Id") == "1");

        if (employee != null) {
            employee.Element("Salary")!.Value = "50000";
            doc.Save(filePath);
            Console.WriteLine("Employee salary updated successfully.");
        }
        else {
            Console.WriteLine("Employee not found.");
        }
    }
}
See this working demo

How This Code Works

Important: The null-forgiving operator (!) assumes that the Salary element exists. In production applications, validate the element before updating it.

Safely Updating XML with Validation

When working with XML files, you should never assume that the requested element or attribute exists.

An XML document may be incomplete, malformed, or contain unexpected values.

A safer implementation checks the required elements before making changes.

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

class Program
{
    static void Main()
    {
        string filePath = "Employees.xml";

        try
        {
            XDocument doc = XDocument.Load(filePath);

            XElement employee = doc
                .Descendants("Employee")
                .FirstOrDefault(e =>
                    (string)e.Attribute("Id") == "1");

            if (employee == null)
            {
                Console.WriteLine("Employee not found.");
                return;
            }

            XElement salaryElement = employee.Element("Salary");

            if (salaryElement == null)
            {
                Console.WriteLine("Salary element is missing.");
                return;
            }

            if (!decimal.TryParse(salaryElement.Value, out _))
            {
                Console.WriteLine("Invalid salary value.");
                return;
            }

            salaryElement.Value = "50000";

            doc.Save(filePath);

            Console.WriteLine("XML updated successfully.");
        }
        catch (System.Xml.XmlException ex)
        {
            Console.WriteLine("Invalid XML: " + ex.Message);
        }
        catch (System.IO.IOException ex)
        {
            Console.WriteLine("File operation failed: " + ex.Message);
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Access denied: " + ex.Message);
        }
    }
}

This approach helps prevent common errors when XML files contain missing elements, invalid values, or unexpected structures.

Updating XML Attributes Using LINQ

Sometimes, you need to update an XML attribute rather than an element value.

For example, suppose we want to change the employee ID from 1 to 101.

XDocument doc = XDocument.Load("Employees.xml");

XElement employee = doc
    .Descendants("Employee")
    .FirstOrDefault(e =>
        (string)e.Attribute("Id") == "1");

if (employee != null)
{
    XAttribute idAttribute = employee.Attribute("Id");

    if (idAttribute != null)
    {
        idAttribute.Value = "101";
    }

    doc.Save("Employees.xml");
}

You can also update an existing attribute like this:

employee?.SetAttributeValue("Id", "101");

The SetAttributeValue() method creates the attribute if it does not already exist or updates it if it does.

Updating XML Data Using DataSet in C#

Another approach is to use the DataSet class.

A DataSet represents data in tables, rows, and columns. It is particularly useful when working with XML that follows a tabular structure.

Example:

using System;
using System.Data;

class Program
{
    static void Main()
    {
        string filePath = "Employees.xml";

        DataSet dataSet = new DataSet();

        dataSet.ReadXml(filePath);

        if (!dataSet.Tables.Contains("Employee"))
        {
            Console.WriteLine("Employee table not found.");
            return;
        }

        DataTable employeeTable = dataSet.Tables["Employee"]!;

        foreach (DataRow row in employeeTable.Rows)
        {
            if (row["Id"].ToString() == "1")
            {
                row["Salary"] = "50000";
                break;
            }
        }

        dataSet.WriteXml(filePath, XmlWriteMode.IgnoreSchema);

        Console.WriteLine("XML data updated successfully.");
    }
}

Note: DataSet maps XML into relational tables. The resulting XML structure may differ from the original, particularly when the XML contains nested elements, attributes, namespaces, or complex relationships.

For XML documents where preserving the original structure is important, LINQ to XML is generally the better choice.

How to Save XML Data Safely

Directly overwriting an XML file can cause data loss if an application crashes or the write operation fails.

For important XML files, consider saving the modified document to a temporary file before replacing the original. For example,

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

class Program
{
    static void Main()
    {
        string filePath = "Employees.xml";
        string tempPath = filePath + ".tmp";

        try
        {
            XDocument doc = XDocument.Load(filePath);

            XElement employee = doc
                .Descendants("Employee")
                .FirstOrDefault(e =>
                    (string)e.Attribute("Id") == "1");

            if (employee == null ||
                employee.Element("Salary") == null)
            {
                Console.WriteLine("Employee or salary not found.");
                return;
            }

            employee.Element("Salary")!.Value = "50000";

            doc.Save(tempPath);

            // Validate the saved temporary XML.
            XDocument.Load(tempPath);

            // Replace the original file.
            File.Move(tempPath, filePath, true);

            Console.WriteLine("XML file updated safely.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error updating XML: " + ex.Message);
        }
        finally
        {
            if (File.Exists(tempPath))
            {
                File.Delete(tempPath);
            }
        }
    }
}

This example reduces the risk of leaving a partially written XML file.

For production systems, also consider file locking, concurrent updates, backups, and recovery procedures. Atomic replacement guarantees depend on the filesystem and platform.

Conclusion

Updating XML data in C# is straightforward when you use the right tools. LINQ to XML provides a flexible approach for modifying XML elements, attributes, and values while maintaining better control over the document structure.

DataSet is a good alternative when XML represents relational or tabular data that needs to be manipulated using rows and columns.

For most XML-specific update operations, LINQ to XML is the recommended starting point. By adding proper validation, exception handling, and safe file-saving techniques, you can make XML updates more reliable and maintainable in your .NET applications.

← Previous