Friday, November 14, 2008

How To populating DropDownList control from XML data





<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="PopulateDropDwonListWithXML.aspx.cs"
Inherits="PopulateDropDwonListWithXML" %>


<!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 runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddlXml" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;

public partial class PopulateDropDwonListWithXML : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("DropDown.xml"));
XmlNodeList nodeList = doc.SelectNodes("//DESTINATIONS/DESTINATION");

foreach (XmlNode node in nodeList)
{
ddlXml.Items.Add(new ListItem(node.SelectSingleNode("NAME").InnerText));
}
}



}





DropDown.XML
<?xml version="1.0" encoding="utf-8" ?>

<GATEWAYS>
<GATEWAY>
<CODE>YXX</CODE>
<NAME>Abbotsford</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>

<GATEWAY>
<CODE>YKF</CODE>
<NAME>Kitchener</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>CUN</CODE>
<NAME>Cancun</NAME>
</DESTINATION>
<DESTINATION>
<CODE>X24</CODE>
<NAME>Cancun (Mayan Riviera)</NAME>
</DESTINATION>
<DESTINATION>
<CODE>POP</CODE>
<NAME>Puerto Plata</NAME>
</DESTINATION>
<DESTINATION>
<CODE>PUJ</CODE>
<NAME>Punta Cana</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
<GATEWAY>
<CODE>YQL</CODE>
<NAME>Lethbridge</NAME>
<DESTINATIONS>
<DESTINATION>
<CODE>PVR</CODE>
<NAME>Puerto Vallarta</NAME>
</DESTINATION>
</DESTINATIONS>
</GATEWAY>
</GATEWAYS>

No comments:

Counter