0

每当它尝试添加包标题信息和其他属性但属性存在并且选择了正确的包时,我都会收到空引用异常

继承人的代码:

private void categorylist_listview_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            XmlDocument LoadPackageList = new XmlDocument();
            //Removes the text "Select A Category" and refrehes the form
            packagelist_listbox.Items.Remove(SelectaCategory_listbox);

            if (categorylist_listview.SelectedItem == WWW_listviewitem)
            {
                LoadPackageList.Load("www.xml");
                XmlNodeList WWWPackageList = LoadPackageList.SelectNodes("/Packages/*");
                int countthenodes = 0;
                foreach (XmlNode WWWPackages in WWWPackageList)
                {
                    //Cycles through all the packages and assings them to a string then adds it to the packagelist
                    countthenodes++;
                    PackageTitle[countthenodes] = WWWPackages.Attributes["title"].ToString();
                    PackageInfo[countthenodes] = WWWPackages.Attributes["info"].ToString();
                    PackageDownloadUrl[countthenodes] = WWWPackages.Attributes["downloadurl"].ToString();
                    PackageTags[countthenodes] = WWWPackages.Attributes["tags"].ToString();
                    packagelist_listbox.Items.Add(PackageTitle[countthenodes]);
                }
                Refresh(packagelist_listbox);

            }
        }

它在 PackageTitle[countthenodes] = WWWPackages.Attributes["title"].ToString(); 处出错

XML 文件:

<Packages>
  <Firefox title="Mozilla Firefox" tags="www firefox web browser mozilla" info="http://google.com" downloadurl="http://firefox.com"></Firefox>


</Packages>

变量被声明

        public string[] PackageTags;
        public string[] PackageTitle;
        public string[] PackageInfo;
        public string[] PackageDownloadUrl;

在文件的最开始

4

1 回答 1

2

嗯,第一个问题是调用ToString()anXmlAttribute不会做你想做的事。您应该使用该Value属性。NullReferenceException但是,除非数据与您显示的不完全一样,否则我认为这不会导致。这是一个简短但完整的程序,可以正常工作:

using System;
using System.Xml;

class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        doc.Load("test.xml");        
        XmlNodeList list = doc.SelectNodes("/Packages/*");
        foreach (XmlNode node in list)
        {
            Console.WriteLine(node.Attributes["title"].Value);
        }
    }
}

这将显示带有您提供给我们的 XML 的“Mozilla Firefox”。

选项:

  • Your real XML actually contains an element without a title attribute
  • Perhaps PackageTitle is null?

It would help if you could produce a short but complete program demonstrating the problem. Ideally it should avoid using a GUI - I can't see anything here which is likely to be GUI-specific.

If you could tell us more about PackageTitle and how it's being initialized, that would help too. How are you expecting it to just keep expanding for as many elements as you find? Or is it an array which is initialized to a larger size than you ever expect to find elements?

于 2009-12-05T19:37:56.680 回答