How can I save all my Data into a Local XML File? I want to be able to load, save and edit different Students. I used .txt file to save all the data in combination with Json, however I now would like to swap to XML. How would I do that?
Cheers
PS: I'm using C# Visual Studio
public partial class Form1 : Form
{
string FilePath = (@"d:\Entwicklung\dotNET\HKC\Übungsaufgaben\WindowsFormsApp2\StudentList.txt");
BindingList<Student> StudentCollection = new BindingList<Student>();
private void btnLaden_Click(object sender, EventArgs e)
{
Student StudentLoad = (Student)cbxStudentIDs.SelectedItem;
txtStudentID.Text = StudentLoad.ID;
txtFirstName.Text = StudentLoad.FirstName;
txtLastName.Text = StudentLoad.LastName;
txtSchoolClass.Text = StudentLoad.Schoolclass;
nudAge.Value = StudentLoad.Age;
nudHeight.Value = StudentLoad.Height;
cbxGender.Text = StudentLoad.Gender;
}
private void btnAddStudent_Click(object sender, EventArgs e)
{
Student StudentSave = new Student
{
ID = txtStudentID.Text,
FirstName = txtFirstName.Text,
LastName = txtLastName.Text,
Age = nudAge.Value,
Height = nudHeight.Value,
Schoolclass = txtSchoolClass.Text,
Gender = cbxGender.Text,
};
cbxStudentIDs.DataSource = StudentCollection;
cbxStudentIDs.DisplayMember = "ID";
StudentCollection.Add(item: StudentSave);
}
public class Student
{
//Eigenschaften
public string ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Age { get; set; }
public decimal Height { get; set; }
public string Schoolclass { get; set; }
public string Gender { get; set; }
}
private void Form1_Load(object sender, EventArgs e)
{
string studentCollectionString = File.ReadAllText(FilePath);
JsonConvert.DeserializeObject<BindingList<Student>>(studentCollectionString)?.ToList().ForEach(a => StudentCollection.Add(a));
cbxStudentIDs.DataSource = StudentCollection;
cbxStudentIDs.DisplayMember = "ID";
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
string studentCollectionString = JsonConvert.SerializeObject(StudentCollection);
File.WriteAllText(FilePath, studentCollectionString);
}
}```