在文本框控件中显示xml文件

时间:2016-10-08 08:53:21

标签: c#

        XmlDocument studentData;
        XmlNodeList studentList;
        TotalClass totalClass = null;
        string gender = "";

        studentData = new XmlDocument();
                studentData.LoadXml("<root>"
                    + "<STUDNT ID=\"7\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"16\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"22\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"25\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"27\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"32\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"35\" Gender=\"f\"></STUDNT>"
                    + "<STUDNT ID=\"45\" Gender=\"M\"></STUDNT>"
                    + "<STUDNT ID=\"4423453244\" Gender=\"F\"></STUDNT>"
                    + "<STUDNT ID=\"44344\" Gender=\"F\"></STUDNT>"
                    + "</root>");

        studentList = studentData.SelectNodes("//STUDENT");
        if(studentList != null && studentList.Count > 0)
        {
            foreach(XmlElement student in studentList)
            {
                gender = student.GetAttribute("Gender");
                switch(gender)
                {
                    case "F":
                        totalClass.Females++;   
                        break;

                    default:
                    case "M":
                        totalClass.Males++;                           
                        break;
                }

            }// end loop


        }

        this.lblMales.Text = totalClass.Males.ToString ();      
        this.lblFemale.Text = totalClass.Females.ToString();
        this.lblTotal.Text = (totalClass.Females + totalClass.Males).ToString();

我需要一些这方面的帮助。 我被分配调试这个程序,我找不到解决方法。点击计数按钮后继续获取NullReferenceException

2 个答案:

答案 0 :(得分:0)

您的totalClass对象为空。在你的foreach之前,宣布你的课程。你可以默认使用它。

studentList = studentData.SelectNodes("//STUDENT");
totalClass = new TotalClass();//add this.

阅读这个问题,它几乎是堆栈溢出中C#的着名问题: What is a NullReferenceException, and how do I fix it?

答案 1 :(得分:0)

尝试像这样修改

studentList = studentData.SelectNodes(&#34; / root / STUDNT&#34;);

并修改为

totalClass = new TotalClass();