I try to read data from a Xml file. My plan is to save all students as an object of Student with the name and the semester.
<persons>
<student><name>255211</name><semester>MI</semester></student>
<student><name>255212</name><semester>MI</semester></student>
<student><name>255213</name><semester>MI</semester></student>
</persons>
I found a guide with XmlReader and switch case so i tried it.
private static void readData()
{
XmlTextReader reader = new XmlTextReader("data.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "student":
Student student = new Student();
Students.Add(student);
break;
case "name":
student.name = reader.ReadString();
//Console.WriteLine(student.name);
break;
case "semester":
student.semester = reader.ReadString();
break;
}
}
}
reader.Close();
}
My problem now is that Visual Studio Code gives me an error: error CS0165: Use of unassigned local variable 'student' (student.name in case "name"). I guess it is because there wouldn't be a student.name if the code does not go into case "student". I tried with try catch but that didn't helped me.
How can I achieve that every student gets his name and semester correct?