Monday, February 7, 2011

LINQ to XML Example with Source Code

Download Source Code
ASP.NET XML Tutorial

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:

<?xml version="1.0" encoding="utf-8"?>
<Persons>
<Person>
<Name>Ella</Name>
<City>LA</City>
<Age>13</Age>
</Person>
<Person>
<Name>Ingrid</Name>
<City>Oslo</City>
<Age>63</Age>
</Person>
</Persons>
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:
<form id="form1" runat="server">
<strong>Add to XML</strong><br />
Name:<br />
<asp:TextBox ID="txtName" runat="server" /><br />
City:<br />
<asp:TextBox ID="txtCity" runat="server" /><br />
Age:<br />
<asp:TextBox ID="txtAge" runat="server" /><br />
<asp:Button ID="butAdd" runat="server" Text="Add" /><br />
<asp:Label ID="lblStatus" runat="server" />
<br /><br />
<strong>Read XML:</strong><br />
<asp:Button ID="butRead" runat="server" Text="Read" /><br />
<asp:Literal ID="litResults" runat="server" />
</form>

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:
protected void butRead_Click(object sender, EventArgs e)
{

}

protected void butAdd_Click(object sender, EventArgs e)
{

}
<asp:Button ID="butAdd" runat="server" Text="Add" onclick="butAdd_Click" /><br />
..
<asp:Button ID="butRead" runat="server" Text="Read" onclick="butRead_Click" /><br />
We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.
In the code-behind, we will add a method that will read the XML data from the file:
protected void readXML()
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

var persons = from person in xmlDoc.Descendants("Person")
select new
{
Name = person.Element("Name").Value,
City = person.Element("City").Value,
Age = person.Element("Age").Value,
};

litResults.Text = "";
foreach (var person in persons)
{
litResults.Text = litResults.Text + "Name: " + person.Name + "<br />";
litResults.Text = litResults.Text + "City: " + person.City + "<br />";
litResults.Text = litResults.Text + "Age: " + person.Age + "<br /><br />";
}

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

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:
protected void butRead_Click(object sender, EventArgs e)
{
readXML();
lblStatus.Text = "";
}
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:
protected void butAdd_Click(object sender, EventArgs e)
{
try
{
if(txtName.Text == "" || txtCity.Text == "" || txtAge.Text == "")
lblStatus.Text = "Please complete the form.";
else
{
XDocument xmlDoc = XDocument.Load(Server.MapPath("People.xml"));

xmlDoc.Element("Persons").Add(new XElement("Person", new XElement("Name", txtName.Text),
new XElement("City", txtCity.Text), new XElement("Age", txtAge.Text)));

xmlDoc.Save(Server.MapPath("People.xml"));
lblStatus.Text = "Data successfully added to XML file.";
readXML();
}
}
catch
{
lblStatus.Text = "Sorry, unable to process request. Please try again.";
}
}

No comments:

Post a Comment