我不想覆盖 XML 文件中的数据我想将新旧数据保存在 XML 文件中。
我有一个三类:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Person()
{
}
public override string ToString()
{
return FirstName + " " +LastName + "\t" +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 int RoomNumber { get; set; }
public override string ToString()
{
return base.ToString() + "," + RoomNumber;
}
}
我还有一门课,我只是从 PeronDB (类)中调用数据
public class Persons
{
private List<Person> persons = null;
public void Save()
{
PersonDB.SavePersons(persons);
}
}
我正在做的 InPersonDB 类将整个数据保存在 XML 文件中,但它会覆盖
public class PersonDB
{
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)
{
if (typeof(Student).IsInstanceOfType(person))
{
AppendStudentInfo(person, xmlOut);
}
else if (typeof(Teacher).IsInstanceOfType(person))
{
AppendTeacherInfo(person, xmlOut);
}
else
{
AppendPersonInfo(person, xmlOut);
}
}
xmlOut.WriteEndElement();
xmlOut.Close();
}
在我正在做的 Form_Load 事件中:
Persons personList = null;
private void FillPersonlstBox()
{
Person p;
listBox1.Items.Clear();
for (int i = 0; i < personList.Count; i++)
{
p = personList[i];
listBox1.Items.Add(p.ToString());
}
}
private void Save_Click(object sender, EventArgs e)
{
HandleChange(personList);
}
private void Form1_Load(object sender, EventArgs e)
{
personList.Changed += new Persons.ChangeHandler(HandleChange);
}
private void HandleChange(Persons Persons)
{
Persons.Save();
FillPersonlstBox();
}
private void Load_Click(object sender, EventArgs e)
{
personList.Changed += new Persons.ChangeHandler(HandleChange);
personList.Fill();
FillPersonlstBox();
}
当我单击保存按钮时,它会覆盖数据,它会删除旧数据并保存新数据,即使我按下第一个加载按钮并加载数据,然后在保存按下按钮后添加更多数据,它仍然会覆盖..