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

本文关键字:显示 xml 文件 控件 文本 | 更新日期: 2023-09-27 18:12:04

        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

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

您的totalClass对象为空。在学习之前,声明你的类。您可以使用默认设置。

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

阅读这个问题,它几乎是c#中堆栈溢出的著名问题:什么是NullReferenceException,我如何修复它?

尝试这样修改

studentList = studentData.SelectNodes("/root/studentt ");

并修改为