开发者

Error loading contents from a XML file into a dropdownlist

private void BindCountry()
{
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("countries.xml"));

    foreach (XmlNode node in doc.SelectNodes("//country"))
    {
        usrlocationddl.Items.Add(new ListItem(node.InnerText, node.Attributes["codes"].InnerText));
    }
}

The above code am using for loading countries List from an xml file into a dropdown list. But while doing so am encountering a Null Reference error.

Object reference not set to an i开发者_运维技巧nstance of an object.

Contents of the xml file:

<countries>
  <country code="AF" iso="4">Afghanistan</country>
  <country code="AL" iso="8">Albania</country>
</countries>

Where in the code should I be changing, so that I can escape the error.


I suspect the problem is that you've got a country with no "codes" attribute. You could avoid that like this:

private void BindCountry()
{
    XmlDocument doc = new XmlDocument();
    doc.Load(Server.MapPath("countries.xml"));

    foreach (XmlNode node in doc.SelectNodes("//country"))
    {
        XmlAttribute attr = node.Attributes["codes"];
        if (attr != null)
        {
            usrlocationddl.Items.Add(new ListItem(node.InnerText, attr.Value));
        }
    }
}

If that doesn't help, I suggest you write a simple console application to try to load the XML and write out each entry you'd select - that should make it easier to work out what's going wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜