This tutorial will show you how to use LINQ to XML to read and also add data to an external XML file, in C#.

XML can make a great storage medium for smaller, less sensitive data. In this tutorial, you will learn how to use LINQ to XML in ASP.NET 3.5 to add data to an external XML file, and also display the data on the page.

We will start by creating a new C# web application project in Visual Studio, and then add an XML file by right-clicking on the project in Solution Explorer, then choose Add New Item.. XML File.
In this example, we will use the XML file to store the names, city and age of numerous people. Our XML structure will look like this:

Next, we will build our ASPX page to be able to display the XML data as well as add new nodes. We will use textboxes and a button to add new data, and then a Literal control to display the existing data:

Now if we go into Design view of our ASPX page, we can double-click on the buttons to create the on click event handlers for them. This will add the following into the back-end, and also add the onclick attributes to the ASPX page:

In the code-behind, we will add a method that will read the XML data from the file:

This method makes use of LINQ to select all the data from the XML file, and then display it in the Literal control by looping through each item.
Next, we can add code to the button handlers. For the Read button, we will simply reference the method we just created, then set the status label to nothing:

The Add button will make use of LINQ also, after checking to see if all text boxes were filled, opening the XML file and adding a new node to the file:

When running this web application, we are able to view the data from the XML file and also add new data to it using the form we created. To enhance it, we could add an UpdatePanel to use Asynchronous Postbacks.
Download Source Files