Click here to Skip to main content
15,400,433 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have the following xml file in key/value pair form:
XML
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root>
  <row>
    <var name="CountryId" value="1" />
    <var name="Country" value="Afghanistan" />
    <var name="FIPS104" value="AF" />
  </row>
  <row>
    <var name="CountryId" value="2" />
    <var name="Country" value="Albania" />
    <var name="FIPS104" value="AL" />
  </row>
  <row>
    <var name="CountryId" value="3" />
    <var name="Country" value="Algeria" />
    <var name="FIPS104" value="AG" />
  </row>
</root>

I need to load this xml document, process it and populate it in a dropdownlist on a webpage via Microsoft Visual Web Developer 2010.

I was trying to do it via XmlNodeList and looping through each XmlNode, but everything I've tried has given me errors!
This is the code in my .cs file.
C#
// Country processing
protected void SetCountryDropDownList()
{
    XmlDocument xmlCountryDocument = new XmlDocument();
    xmlCountryDocument.Load(XML_FILE_PATH2);
    if (!(xmlCountryDocument == null))
    {

        XmlNodeList countryList = xmlCountryDocument.SelectNodes("root/row");

        foreach (XmlNode countryNode in countryList)
        {
            if (countryNode.Name == "CountryId")
                DropDownListCountry.Items.Add(countryNode.Value.ToString());
        }
    }
}

This is the code in my .aspx file.
ASP.NET
<tr>
                    <td align="left" class="paddingRight"></td>
                    <td align="left" class="paddingRight">
                        <asp:label ID="LabelCountry" class="lbl" text="Country:" runat="server" xmlns:asp="#unknown"></asp:label>
                    </td>
                    <td>
                        <asp:DropDownList ID="DropDownListCountry" class="droplist" xmlns:asp="#unknown" Width="195px"
                            ToolTip="Select the country where the trailer currently resides" runat="server" 
                            DataTextField="Country" DataValueField="CountryId" AutoPostBack="True"
                             AppendDataBoundItems="True" onselectedindexchanged="DropDownListCountry_SelectedIndexChanged"></asp:DropDownList>
                    </td>
                    <td align="left" class="paddingRight"></td>
                </tr>

I know that I'm doing something wrong, but I can't figure it out!
I've tried using IDictionary...i.e.,
IDictionary<string, string> keyValuePairList = new Dictionary<string, string>();
and trying to process it, but I'm coming back with errors.

Any help would be greatly appreciated!!
Thanks!
Cindy
Posted
Updated 14-Feb-12 15:15pm
v2
Comments
Sergey Alexandrovich Kryukov 14-Feb-12 21:56pm
   
"Given me errors" and "coming back with errors" is not informative.
Why should anyone do this guesswork or even read you code if you conceal some information. If you want help, help us to help you.

You requirements for population of the list are not formulated, not even by example.

--SA
Cindy MCS 14-Feb-12 22:38pm
   
Well, I honestly don’t know what else you want for me. What I submitted was in bone structure, so it is not giving me errors, but it is not populating my dropdownlist with the countries either. It is blank.
The XML_FILE_PATH2 is valid. I do not get any errors when I load the xmlDocument and it is not null.
The actual xml file has 275 as far as a count of entries, which is about right for the countries in the world.

My Default.aspx.cs has the following:
using System;
using System.Collections.Generic;
using System.Linq;
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;
using System.Data;
using System.IO;
using System.Text;


public partial class TrailerInitialization : System.Web.UI.Page
{
string XML_FILE_PATH = "C:\\Temp\\Websites\\TrailerInitializeTest\\Resources\\TheWorld.xml";
string XML_FILE_PATH2 = "C:\\Temp\\Websites\\TrailerInitializeTest\\Resources\\Countries.xml";

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetCountryDropDownList();
}
}

// Trailer name processing
protected void TextBoxName_TextChanged(object sender, EventArgs e)
{

}

// Country processing
protected void SetCountryDropDownList()
{
XmlDocument xmlCountryDocument = new XmlDocument();
xmlCountryDocument.Load(XML_FILE_PATH2);
if (!(xmlCountryDocument == null))
{

//XmlNodeList countryList = xmlWorldDocument.SelectNodes("world/countries/country");
//XmlNodeList countryList = xmlWorldDocument.SelectNodes("countries/country/countryName");
XmlNodeList countryList = xmlCountryDocument.SelectNodes("root/row");

ShowPopUpMsg(Convert.ToString(countryList.Count));
foreach (XmlNode countryNode in countryList)
{

foreach (XmlNode innerNode in countryNode.ChildNodes)
{
if (countryNode.Name == "CountryId")
DropDownListCountry.Items.Add(countryNode.Value.ToString());
}
}


}
}
protected void DropDownListCountry_SelectedIndexChanged(object sender, EventArgs e)
{
}


public void ShowPopUpMsg(string msg)
{
StringBuilder sb = new StringBuilder();
sb.Append("alert('");
sb.Append(msg.Replace("\n", "\\n").Replace("\r", "").Replace("'", "\\'"));
sb.Append("');");
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", sb.ToString(), true);
}
}

And my Default.aspx has the following…

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

<!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></title>


<style type="text/css">
.styleBody{font-family: Arial; Position: absolute; Top: 0; Left: 0; right: 0;height: 516px;}
.styleHeader{font-family: Arial; color: #FF5050; font-size: x-large;}
.lbl{font-family: Arial; color: #000066; font-weight: 700;}
.txtbox{font-family: Arial; color: #000066; font-weight:600;}
.droplist{font-family: Arial; color: #000066; font-weight:600;}
.paddingRight{padding-right: 10px;}
</style>

<script language="javascript" type="text/javascript">
// <![CDATA[

function Name_onclick() {

}

// ]]>
</script>

<script language="javascript" type="text/javascript">
</script>

</head>

<body>
<form id="form1" runat="server">
<div class="styleBody">
<asp:Image ID="CommandCenter" runat="server" Height="180px" W
Keith Barrow 15-Feb-12 3:48am
   
The actual error message would be a start. What you have done is like taking a car to a mechanic and saying "There is something wrong with my car" and walking off. Of course the mechanic would be happy, you've just given him an excuse to spend [paid] *hours* looking for the problem. Here we are all unpaid volunteers (except for a few staff members) so we aren't going to do this.

1 solution

Hi Cindy,

Could you please try this piece of code.

Web page :
ASP.NET
<asp:DropDownList runat="server" ID="DropDownListCountry" DataTextField="CountryName" DataValueField="CountryId"></asp:DropDownList>


Code behind :
C#
protected void Page_Load(object sender, EventArgs e)
        {
            LoadCountry();
        }

        void LoadCountry()
        {
            var countries = GetCountries();
            DropDownListCountry.DataSource = countries;
            DropDownListCountry.DataBind();
        }

        private IList<Country> GetCountries()
        {
            string XML_FILE_PATH2 = "C:\\Temp\\Websites\\TrailerInitializeTest\\Resources\\Countries.xml";

            //string XML_FILE_PATH2 = Path.Combine(Server.MapPath("~/Resources"), "Countries.xml");

            IList<Country> countries = new List<Country>();

            XmlDocument xmlCountryDocument = new XmlDocument();
            xmlCountryDocument.Load(XML_FILE_PATH2);
            if (!(xmlCountryDocument == null))
            {

                XmlNodeList countryList = xmlCountryDocument.SelectNodes("root/row");

                foreach (XmlNode countryNode in countryList)
                {
                    string countryId = string.Empty;
                    string country = string.Empty;
                     string countryCode = string.Empty;

                    foreach (XmlNode varElement in countryNode.ChildNodes)
                    {
                        switch (varElement.Attributes["name"].Value)
                        {
                            case "CountryId":
                                countryId = varElement.Attributes["value"].Value;
                                break;
                            case "Country":
                                country = varElement.Attributes["value"].Value;
                                break;
                            case "FIPS104":
                                countryCode = varElement.Attributes["value"].Value;
                                break;
                        }
                    }

                    countries.Add(new Country()
                                      {
                                          CountryId = countryId,
                                          CountryName = country,
                                          CountryCode = countryCode
                                      });
                }
            }

            return countries;
        }


        public class Country
        {
            public string CountryName { get; set; }
            public string CountryId { get; set; }
            public string CountryCode { get; set; }
        }


Please mark your question as solve if this solve your issue.
   
v2
Comments
Cindy MCS 15-Feb-12 9:53am
   
Michael,
Thank you so much!!! It worked with no errors and it populated my drop down list box with all the country names!!
I will definitely keep this in mind as I move forward because I'm sure I will come across list value-pairs in the future!
Thanks again!
Cindy
Michael dg 15-Feb-12 10:03am
   
You are welcome. Enjoy your coding!
by the way you should add the checking for null values in varElement.Attributes["value"].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900