我有三个类,我想在一个 XML 文件中添加所有类数据?
第一类是:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public override string ToString()
{
return FirstName + " " +LastName + " " +Email;
}
}
第二类是:
public class Student:Person
{
public Student()
{
}
public double AssessmentGrade { get; set; }
public double AssignmentGrade { get; set; }
public override string ToString()
{
return base.ToString() + "," +AssessmentGrade + "," + AssignmentGrade;
}
}
第三类是:
public class Teacher:Person
{
public string RoomNumber
{
get;
set;
}
public override string ToString()
{
return base.ToString() + "," + RoomNumber;
}
}
我也创建了一个 DB 类,将所有数据存储在 XML 文件中。
private const string path = @"Persons.xml";
Public static void SavePersons(List<Person> Persons)
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
XmlWriter xmlOut = XmlWriter.Create(path, settings);
xmlOut.WriteStartDocument();
xmlOut.WriteStartElement("Persons");
foreach (Person person in Persons)
{
Student student = new Student();
Teacher teacher = new Teacher();
xmlOut.WriteStartElement("Person");
xmlOut.WriteAttributeString("Email", person.Email);
xmlOut.WriteElementString("Firstname", person.FirstName);
xmlOut.WriteElementString("Lastname", person.LastName);
xmlOut.WriteElementString("AssessmentGrade",
student.AssessmentGrade.ToString());
xmlOut.WriteElementString("AssignmentGrade",
student.AssignmentGrade.ToString());
xmlOut.WriteElementString("Room", teacher.RoomNumber.ToString());
xmlOut.WriteEndElement();
}
xmlOut.WriteEndElement();
xmlOut.Close();
}
现在的问题是如何在同一个 XML 中添加学生类和教师类。我尝试添加但它不起作用。你能帮帮我吗?