0
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));
    }
}

上面的代码用于将 xml 文件中的国家列表加载到下拉列表中。但这样做时遇到空引用错误。

你调用的对象是空的。

xml文件的内容:

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

我应该在代码中的哪个位置进行更改,以便我可以逃避错误。

4

1 回答 1

1

我怀疑问题在于您的国家/地区没有“代码”属性。你可以避免这样的:

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));
        }
    }
}

如果这没有帮助,我建议您编写一个简单的控制台应用程序来尝试加载 XML 并写出您选择的每个条目——这样可以更容易地找出问题所在。

于 2010-04-05T07:33:53.613 回答