WinForm里序列化读写XML
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}岁"; } } }
本文作者:Love In Winter
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/14592721.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/14592721.html
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
![扫一扫,支付宝打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E6%94%AF%E4%BB%98%E5%AE%9D.bmp)
![扫一扫,微信打赏](https://files.cnblogs.com/files/LifeDecidesHappiness/%E5%BE%AE%E4%BF%A1%E6%94%B6%E6%AC%BE%E7%A0%81.bmp)