用NET自带的XML序列化工具进行系列化和反序列化;
需要引用的命名空间:
using System.Xml;
using System.Xml.Serialization;
XmlSerializer serializer = new XmlSerializer(typeof(Student)); using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate)) { serializer.Serialize(stream, student); }
对核心代码制作的数据流程图,以便于理解数据流向和工作原理;
serializer.Serialize(stream, student);
窗口设计
测试用学生类
public class Student { private string m_Name; private string m_Sex; private int m_Age; public string Name { get => m_Name; set => m_Name = value; } public string Sex { get => m_Sex; set => m_Sex = value; } public int Age { get => m_Age; set => m_Age = value; } public string Say() { return $"my name is {Name}"; } }
将学生类进行序列化,并保存至XML文件,测试读取XML文件内容
string path = Application.StartupPath + @"\data.xml"; Student student = new Student() { Name = "孙悟空", Sex = "男", Age = 5000 }; /// <summary> /// 序列化,并读取XML /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { listBox1.Items.Clear(); XmlSerializer serializer = new XmlSerializer(typeof(Student)); using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate)) { serializer.Serialize(stream, student); } XmlDocument doc = new XmlDocument(); if (File.Exists(path)) doc.Load(path); else return; XmlNode root = doc.DocumentElement; listBox1.Items.Add(root.InnerText); bool b = root.HasChildNodes; listBox1.Items.Add("root.HasChildNodes?"+b); XmlNodeList list= root.ChildNodes; listBox1.Items.Add("子节点个数?" + list.Count); foreach (XmlNode item in list) { listBox1.Items.Add(item.InnerText); } }
点击加载按钮--加载XML文件并进行反序列化
/// <summary> /// 加载XML,反序列化 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button2_Click(object sender, EventArgs e) { if (!File.Exists(path)) return; XmlSerializer serializer = new XmlSerializer(typeof(Student)); using (FileStream stream = new FileStream(path, FileMode.Open)) { Student student2 = serializer.Deserialize(stream) as Student; listBox1.Items.Clear(); listBox1.Items.Add("反序列化数据"); listBox1.Items.Add("生成类型"+student2.ToString()); listBox1.Items.Add(student2.Name); listBox1.Items.Add(student2.Sex); listBox1.Items.Add(student2.Age); listBox1.Items.Add("Say()" + student2.Say()); } }
结果: