Friday, February 17, 2012

Loading a dropdownlist from an XML file


What are we cooking today?
One Way of loading a dropdownlist from an XML file (sample: reading dates from an XML file)

RECIPE
The XML looks like:

<?xml version="1.0" encoding="utf-8" ?> <dates> <LocationA> <date>February 17, 2012</date> <date>March 29, 2012</date> <date>April 26, 2012</date> </LocationA> <LocationB> <date>March 29, 2012</date> <date>April 26, 2012</date> </LocationB> </dates>


The procedure:

Public Sub LoadDatesFromXMLFile(ByVal strOption As String) Try Dim doc As XDocument = XDocument.Load(MapPath("MyFile.xml")) If strOption = " LocationA " Then For Each element As XElement In doc.Descendants(" LocationA ") For Each XmlNode In element.Descendants("date") ddlAvailableDates.Items.Add(XmlNode.Value) Next Next Else For Each element As XElement In doc.Descendants("LocationB") For Each XmlNode In element.Descendants("date") ddlAvailableDates.Items.Add(XmlNode.Value) Next Next End If Catch ex As Exception lblError.Text = ex.Message End Try End Sub