我不想覆蓋XML文件中的數據我想將舊數據和新數據保存在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();
}
當我點擊保存按鈕,它會覆蓋它刪除舊數據的數據,並保存新的數據,即使我按第一Load按鈕,加載數據,然後以後添加更多的數據我保存按按鈕它仍然覆蓋..
您能否將您的示例代碼縮減爲7-10行?它看起來不像事件處理和其他與表單相關的代碼屬於這個問題。 – 2012-08-16 21:35:18
那麼PersonDB.GetPerson代碼在哪裏呢?你怎麼知道發生了什麼變化?看到你只是從Persons集合重新創建xml,當然它會被覆蓋。所以真正的問題是你最初加載的數據到底在哪裏?哦,鑄件有什麼用?您的每個類都應該具有讀取和寫入xml方法,然後如果您要這樣做,則會以多態方式調用。 – 2012-08-16 21:44:26
你可以請簡單告訴我..我真的需要幫助 – user1050667 2012-08-17 04:11:57