Quantcast
Viewing all articles
Browse latest Browse all 10

Using LINQ to XML to Add Data to XML File in C#

Introduction

In this article, we will be looking at another flavor of Microsoft’s new introduction to the .NET Framework, LINQ to XML. LINQ (Language-Integrated Query) comes in a variety of forms, including LINQ to SQL and LINQ to Objects. In this article, we will be looking at LINQ to XML in Visual Studio.NET 2008. If you do not have 2008, you can download the LINQ Preview for VS.NET 2005 direct from Microsoft.

For this demonstration, we will be using LINQ to XML in a Windows Form to display data from an XML file, and then also having the ability to add new data to the XML file.

What we will learn in this article:
How to retrieve data from an XML file using LINQ;
How to add data to an XML file using LINQ.

Please Note:
LINQ is integrated into ASP.NET 3.5 and does not require any additional downloads. If you are using ASP.NET 2.0, certain extra steps may need to be taken that are not covered in this article.

Getting Started

The first thing we will need to do is create the XML file we will be using. So let’s go ahead and open up Visual Studio and create a new C# Windows Form Application. Once opened, right-click the project in Solution Explorer and choose Add > New Item.. XML File. Name it Players.xml:

Image may be NSFW.
Clik here to view.

(click to enlarge)

Once we have this opened in Visual Studio, we will need to build the structure of the file. For this example, we will use soccer player names, their teams, and their positions. The structure of the XML file will look like this:

<?xml version="1.0" encoding="utf-8" ?>
<Players>
<Player>
<Name>C.Ronaldo</Name>
<Team>Man Utd</Team>
<Position>Midfielder</Position>
</Player>
<Player>
<Name>P.Cox</Name>
<Team>Bayern Munich</Team>
<Position>Midfielder</Position>
</Player>
<Player>
<Name>Z.Cox</Name>
<Team>AC Milan</Team>
<Position>Midfielder</Position>
</Player>
<Player>
<Name>Ole Solskjaer</Name>
<Team>FC Molde</Team>
<Position>Striker</Position>
</Player>
</Players>

Our XML file needs to be correctly structured. Each player resides within the tags, and all reside within the tags.

Once we have completed our XML file, with some sample data, we can start to build our form. We will need to display the XML file on the form, and also provide a way to add new data to the XML file.

To do this, we will add two textboxes, for the name and team elements, and then a combo box for the position element. We will use a combo box to restrict the values that can be input for this element. We will also add two buttons – one to add, and one to read, and then a richtextbox to display the contents of the XML file. Our form will looks something like this:

Image may be NSFW.
Clik here to view.

(click to enlarge)

The large textbox at the bottom of the form is the richtextbox that will be used to display the contents of the XML file. To add options to our combo box, click the Smart Tag in design view and choose Edit Items. Then simply add the items to the box that appears (One option per line, like so:)

Image may be NSFW.
Clik here to view.

(click to enlarge)

Image may be NSFW.
Clik here to view.

(click to enlarge)

We should also change the names of the controls. It is good practice to name the controls you will be working with, particularly if you are going to be referencing them by name in the code-behind. As a good naming convention, name buttons beginning with but, textboxes beginning with txt and labels beginning with lbl, for example. Our textboxes on this form are named txtName and txtTeam; the combobox is named cmbPosition; the buttons are named butAdd and butReadXml; and the richtextbox is named txtResults.

In this example, we are going to create a method for adding data to the XML file, and another method to read the data from the XML file. We can then call these methods from the button click events. This allows us to use the methods more than once, yet only have one instance.

If we double-click one of our buttons on the form design view, we will create an event handler for the click event of that button. We can do it for both buttons and have the following code-behind:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Xml.Linq;
using System.Text;
using System.Windows.Forms;
using System.Linq;

namespace example
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void butAdd_Click(object sender, EventArgs e)
{

}

private void butReadXML_Click(object sender, EventArgs e)
{

}
}
}

Once we have the handlers created, we will create our own methods starting with the readXml method. We will be using LINQ to first load the XML file, and then select all data before looping through the collection to display in the richtextbox. The method is displayed below.

NOTE: When developing and debugging the application in Visual Studio, the programm will not be able to locate the XML file if it is placed in the root directory. To avoid this, copy the XML file to the bin/debug folder when running from Visual Studio.

private void readXml()
{
XDocument xmlDoc = XDocument.Load("Players.xml");

var players = from player in xmlDoc.Descendants("Player")
select new
{
Name = player.Element("Name").Value,
Team = player.Element("Team").Value,
Position = player.Element("Position").Value,
};

txtResults.Text = "";
foreach (var player in players)
{
txtResults.Text = txtResults.Text + "Name: " + player.Name + "\n";
txtResults.Text = txtResults.Text + "Team: " + player.Team + "\n";
txtResults.Text = txtResults.Text + "Position: " + player.Position + "\n\n";
}

if (txtResults.Text == "")
txtResults.Text = "No Results.";
}

There were times in the past when simply parsing an XML file would take many lines of code, but LINQ makes it so easy for us, that we can loop through a file, collect all data within, and display it into a textbox in as few as 15 lines of code.

Adding data to an XML file using LINQ is even easier than reading; we simply need to load the XML file and specify where and what we want to add. Finally, we can save the changes to the XML file. The method to add new data to the XML file is below.

private void addToXml()
{
XDocument xmlDoc = XDocument.Load("Players.xml");

xmlDoc.Element("Players").Add(new XElement("Player", new XElement("Name", txtName.Text),
new XElement("Team", txtTeam.Text), new XElement("Position", cmbPosition.SelectedItem.ToString())));

xmlDoc.Save("Players.xml");
readXml();
}

These two methods will successfully manage our XML data. We can call these methods from our button clicks like so:

private void butAdd_Click(object sender, EventArgs e)
{
addToXml();
}

private void butReadXML_Click(object sender, EventArgs e)
{
readXml();
}

What we have Learned

We have learned how to use LINQ to XML to manipulate XML by loading external XML files and reading the data within, as well as writing data to external XML files also.

Download Source Files

The post Using LINQ to XML to Add Data to XML File in C# appeared first on Programming Help | Web Development and Programming Tutorials.


Viewing all articles
Browse latest Browse all 10

Trending Articles