Here is my problem: I am trying to create an instance of a Student
class which is the return type of the static method too, but for some reason I am getting the error
Object reference not set to an instance of an object
Here is my class
public class Student
{
static string VirtualFPath = "~/App_Data/Students.xml";
public int ID { get; set; }
public string Name { get; set; }
public int CourseID { get; set; }
public static string Serialize(Student student)
{
XElement xElement = new XElement("student", new XAttribute("id", student.ID));
xElement.Add(new XElement("name", student.Name));
xElement.Add(new XElement("course", student.Name));
return xElement.ToString();
}
public static Student Deserialize(string studentxElement)
{
XElement xElement = XElement.Parse(studentxElement);
// error occurs here
Student stud = new Student
{
ID = Convert.ToInt32(xElement.Attribute("id").Value),
Name = xElement.Element("name").Value,
CourseID = Convert.ToInt32(xElement.Element("course").Value)
};
return stud;
}
public static List<Student> GetAllStudents()
{
List<Student> StudentsList = new List<Student>();
XDocument xDoc = XDocument.Load(HttpContext.Current.Server.MapPath(VirtualFPath));
var xStudentElement = from xStudent in
xDoc.Descendants("students")
select xStudent;
foreach (XElement xStudent in xStudentElement)
{
Student student = Student.Deserialize(xStudent.ToString());
StudentsList.Add(student);
}
return StudentsList;
}
}
I call GetAllStudents()
by creating an instance of the Student
class.