Tutorial RSS
 
DB Tutorials Server Intellect Cloud Hosting
Navigator: Home - Retrieve - Using LINQ to Display and Filter XML Data in VB

Using LINQ to Display and Filter XML Data in VB

This tutorial shows an alternative to using a database - using LINQ to retrieve data from an XML file and also how to filter data from XML. C# version.


If you're ever in the market for some great Windows web hosting, try Server Intellect. We have been very pleased with their services and most importantly, technical support.


Looking for more .NET Database Tutorials? Click Here!

Microsoft's new LINQ implementation into the .NET Framework 3.5 makes you look at DataSources in a different way. Not only can you use LINQ to handle databases more easily, it also allows for you to communicate more easily with XML documents and even ASP.NET Controls. In this tutorial, we will look at using an XML document in place of a database. We will see how LINQ makes it easy for us to interact with an XML document, and not only retrieve the data it holds, but also filter the data to retrieve the data that we really want.

We can start off by opening a new project in Visual Studio .NET 2008. If you are using 2005, you can still take advantage of LINQ, but will need to installed the LINQ Preview, which is available from the Microsoft website free of charge.

The first thing we will do is add the namespaces we will be using. Our code-behind will look something like this:

Imports System
Imports System.Configuration
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Xml.Linq
Imports System.Xml


The next thing we will do is add an XML file to our project, and create some sample data. If you have your own existing XML file, then great, but for this example, we are going to use the following XML:

<?xml version="1.0" encoding="utf-8" ?>
<Persons>
<Person>
<Name>Paxton</Name>
<City>Munich</City>
<Age>29</Age>
</Person>
<Person>
<Name>Mike</Name>
<City>Orlando</City>
<Age>33</Age>
</Person>
<Person>
<Name>Ella</Name>
<City>LA</City>
<Age>13</Age>
</Person>
<Person>
<Name>Ingrid</Name>
<City>Oslo</City>
<Age>63</Age>
</Person>
</Persons>


We are going to use this data to display on our ASPX page, and also filter through the data. We will allow the user to specify the data they want to see through the use of a DropDownList - we will let the user filter the data by City. But first, we need to create our Controls. To our ASPX page, we will add a button and a Literal Control. When clicked, the button will retrieve the XML data and display it in the Literal Control. Our ASPX page with these added will look something like this:

<asp:Button ID="butGetXML" runat="server" Text="Get All XML"
onclick="butGetXML_Click" /><br /><br />
<asp:Literal ID="litXMLData" runat="server"></asp:Literal>


We have defined a handler for the click event of this button, and the code-behind will look something like this:

Protected Sub butGetXML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butGetXML.Click
Dim xmlDoc As XDocument = XDocument.Load(Server.MapPath("XMLFile.xml"))

Dim persons = From person In xmlDoc.Descendants("Person") _
Select Name = person.Element("Name").Value, City = person.Element("City").Value, _
Age = person.Element("Age").Value

litXMLData.Text = ""
For Each person In persons
litXMLData.Text = litXMLData.Text & "Name: " & person.Name & "<br />"
litXMLData.Text = litXMLData.Text & "City: " & person.City & "<br />"
litXMLData.Text = litXMLData.Text & "Age: " & person.Age & "<br /><br />"
Next person

If litXMLData.Text = "" Then
litXMLData.Text = "No Results."
End If
End Sub


This block of code will retrieve the data from the XML file and input it into the Literal Control. If there is no data in the XML file, the user will be notified. We are using LINQ in this method, notice how it is similar to SQL Statement - we are using a SELECT keyword, as well as the FROM keyword, except it is the opposite way round to SQL. LINQ is relatively logical in this way, as we are simply selecting the values of Name, City and Age elements of the XML file. We then loop through the data and output it to the Literal Control.
This should now be functional in that if we run it, we will be able to extract all the data from the XML file when the button is clicked. However, we want more functionality than this. We will now add a DropDownList to our ASPX page and populate it with the data from the XML file - we will only want the City nodes, though. Our ASPX page will now look something like this:

<asp:Button ID="butGetXML" runat="server" Text="Get All XML"
onclick="butGetXML_Click" /><br /><br />

Filter data by City:<br />
City: <asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList><br />
<asp:Button ID="butFilterXML" runat="server" Text="Filter XML"
onclick="butFilterXML_Click" /><br /><br />
<asp:Literal ID="litXMLData" runat="server"></asp:Literal>


We have now added a DropDownList and another button. The user will be able to select a City from the DropDownList and then click the button to see data matching his request. Now we need to populate the DropDownList. We will do this on Page Load:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
loadDDL()
End If
End Sub

Protected Sub loadDDL()
Dim doc As New XmlDocument()
doc.Load(Server.MapPath("XMLFile.xml"))
Dim nodeList As XmlNodeList = doc.SelectNodes("Persons/Person")

For Each node As XmlNode In nodeList
ddlCity.Items.Add(New ListItem(node.SelectSingleNode("City").InnerText))
Next node
End Sub

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!


Upon Page Load, the method will be called if the page is not posted back. The method retrieves only the City node within the XML file and adds each item to the DropDownList. This means the user can now select any City that is in the XML file. Next, we need to add the logic to filter the XML data by the user's selection. We will do this on the Filter Button Click event:

Protected Sub butFilterXML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butFilterXML.Click
Dim xmlDoc As XDocument = XDocument.Load("XMLFile.xml")

Dim persons = From person In xmlDoc.Descendants("Person") _
Where person.Element("City").Value = ddlCity.SelectedItem.ToString() _
Select Name = person.Element("Name").Value, City = person.Element("City").Value, _
Age = person.Element("Age").Value

litXMLData.Text = ""
For Each person In persons
litXMLData.Text = litXMLData.Text & "Name: " & person.Name & "<br />"
litXMLData.Text = litXMLData.Text & "City: " & person.City & "<br />"
litXMLData.Text = litXMLData.Text & "Age: " & person.Age & "<br /><br />"
Next person

If litXMLData.Text = "" Then
litXMLData.Text = "No Results."
End If
End Sub


This method is similar to the other button, which retrieves all the data, except it has a WHERE clause in the SELECT statement. We only select the data from the XML file that matches the user request, then we output it to the Literal Control in the same way as before. Now if you run this, we will have the option to get all data from the XML file, or get data matching the City we select from the list.
As an added feature, we can add AJAX to the code to improve the performance - there will be no full page postback if we use the code below, which is the entire ASPX page:

<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Using LINQ to XML - displaying and filtering XML data in Visual Studio 2008 and VB</title>
</head>

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="butGetXML" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Button ID="butGetXML" runat="server" Text="Get All XML"
onclick="butGetXML_Click" /><br /><br />

Filter data by City:<br />
City: <asp:DropDownList ID="ddlCity" runat="server">
</asp:DropDownList><br />
<asp:Button ID="butFilterXML" runat="server" Text="Filter XML"
onclick="butFilterXML_Click" /><br /><br />
<asp:Literal ID="litXMLData" runat="server"></asp:Literal>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>


And the entire code-behind will look something like this:

Imports System
Imports System.Configuration
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Xml.Linq
Imports System.Xml

Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
loadDDL()
End If
End Sub

Protected Sub loadDDL()
Dim doc As New XmlDocument()
doc.Load(Server.MapPath("XMLFile.xml"))
Dim nodeList As XmlNodeList = doc.SelectNodes("Persons/Person")

For Each node As XmlNode In nodeList
ddlCity.Items.Add(New ListItem(node.SelectSingleNode("City").InnerText))
Next node
End Sub

Protected Sub butGetXML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butGetXML.Click
Dim xmlDoc As XDocument = XDocument.Load(Server.MapPath("XMLFile.xml"))

Dim persons = From person In xmlDoc.Descendants("Person") _
Select Name = person.Element("Name").Value, City = person.Element("City").Value, _
Age = person.Element("Age").Value

litXMLData.Text = ""
For Each person In persons
litXMLData.Text = litXMLData.Text & "Name: " & person.Name & "<br />"
litXMLData.Text = litXMLData.Text & "City: " & person.City & "<br />"
litXMLData.Text = litXMLData.Text & "Age: " & person.Age & "<br /><br />"
Next person

If litXMLData.Text = "" Then
litXMLData.Text = "No Results."
End If
End Sub

Protected Sub butFilterXML_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles butFilterXML.Click
Dim xmlDoc As XDocument = XDocument.Load("XMLFile.xml")

Dim persons = From person In xmlDoc.Descendants("Person") _
Where person.Element("City").Value = ddlCity.SelectedItem.ToString() _
Select Name = person.Element("Name").Value, City = person.Element("City").Value, _
Age = person.Element("Age").Value

litXMLData.Text = ""
For Each person In persons
litXMLData.Text = litXMLData.Text & "Name: " & person.Name & "<br />"
litXMLData.Text = litXMLData.Text & "City: " & person.City & "<br />"
litXMLData.Text = litXMLData.Text & "Age: " & person.Age & "<br /><br />"
Next person

If litXMLData.Text = "" Then
litXMLData.Text = "No Results."
End If
End Sub
End Class


We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.





Looking for more .NET Database Tutorials? Click Here!
Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!