Jun
3
Written by:
Steve Gray
6/3/2010 6:46 AM
Recently I had a project where I needed to have a small configuration file/table that a user could maintain, possibly add records to if needed. The overhead to put that in SQL was a little too much – I’d need to write forms for the maintenance, handle security… it would take a bit to do all that.
Instead, it seemed easier to write an XML file to handle the task and to allow the user FTP access to the web site. So, given an XML file, how do I get access to all the fields in one ‘record’? LinqToXML to the rescue.
First, create a class to represent the record
Public Class eCard
Public cardID As Int16
Public image As String
Public imageThumb As String
Public subject As String
Public label As String
End Class
Then, here is code to read the XML file and populate the class. This is a ASP DataList ItemCommand method, the DataList as the ‘cardID’ in the CommandArgument.
Imports System.Data
Imports System.Xml.Linq
Imports System.Linq
Imports System.Xml
Protected Sub lstCards_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) Handles lstCards.ItemCommand
Dim doc = XDocument.Load(Server.MapPath("/eCards/eCard.xml"))
Dim cardID As Int16 = e.CommandArgument
Dim query = _
From c In doc.<cards>.<card> _
Where c.<cardID>.Value = cardID _
Select c
Dim eCard As New eCard
For Each g In query
eCard.cardID = cardID
eCard.image = g.<image>(0).Value
eCard.imageThumb = g.<imageThumb>(0).Value
eCard.subject = g.<subject>(0).Value
eCard.label = g.<label>(0).Value
Next
Session("eCard") = eCard
Response.Redirect("eCards2.aspx")
End Sub