using System; using System.Collections.Generic; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; using MessageBoxEffects.MyClass; namespace WinFormXmlSerializeObjectDemo { /// <summary> /// WinForm里序列化读写XML /// LDH @ 2021-3-29 /// </summary> public partial class FrmMain : Form { public readonly List<Student> StuList = new List<Student>(); public FrmMain() { InitializeComponent(); InitStudents(); } private void InitStudents() { StuList.AddRange(new[] { new Student {Id = 1, Age = 18, Name = "LDH"}, new Student {Id = 2, Age = 28, Name = "Lily"}, new Student {Id = 3, Age = 38, Name = "Lucy"}, new Student {Id = 4, Age = 40, Name = "Tom"}, new Student {Id = 5, Age = 58, Name = "Jerry"} }); } /// <summary> /// 序列化对象,并写入XML文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnWriteIntoXml_Click(object sender, EventArgs e) { var serializer = new XmlSerializer(typeof(List<Student>)); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Student.xml"); using (var stream = new FileStream(path, FileMode.OpenOrCreate)) { serializer.Serialize(stream, StuList); MyHelper.ShowMessageBoxInfo($"成功写入到Xml文件!{Environment.NewLine}文件路径:{path}"); } } /// <summary> /// 读取XML文件,并反序列化为对象,并绑定到ListBox控件进行展示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnReadFromXml_Click(object sender, EventArgs e) { var serializer = new XmlSerializer(typeof(List<Student>)); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Student.xml"); using (var stream = new FileStream(path, FileMode.OpenOrCreate)) { var stuList = serializer.Deserialize(stream); listStudent.DataSource = null; listStudent.BeginUpdate(); listStudent.DataSource = stuList; listStudent.EndUpdate(); } } } public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public override string ToString() { return $"{Id},{Name},{Age}岁"; } } }