[原创]xml序列化

源码包

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Text;
 7 using System.Windows.Forms;
 8 using System.Xml.Serialization;
 9 using System.IO;
10 
11 namespace TestXML
12 {
13     public partial class Form1 : Form
14     {
15         public Form1()
16         {
17             InitializeComponent();
18         }
19 
20         public class TestXML
21         {
22             public string name;
23             public string age;
24             public string sex;
25         }
26 
27         private void button1_Click(object sender, EventArgs e)
28         {
29             TestXML a = new TestXML();
30             a.name = this.textBox1.Text.Trim();
31             a.age = this.textBox2.Text.Trim();
32             a.sex = this.textBox3.Text.Trim();
33 
34             if (this.saveFileDialog1.ShowDialog() ==DialogResult.OK)
35             {
36                 try
37                 {
38                     Stream s = saveFileDialog1.OpenFile();
39                     new XmlSerializer(a.GetType()).Serialize(s, a);
40                     s.Close();
41                 }
42                 catch (Exception ex) 
43                 {
44                     MessageBox.Show(ex.Message);
45                 }
46             }
47         }
48 
49         private void button2_Click(object sender, EventArgs e)
50         {
51             if (openFileDialog1.ShowDialog() == DialogResult.OK)
52             {
53                 try
54                 {
55                     XmlSerializer xs = new XmlSerializer(typeof(TestXML));
56                     Stream s = openFileDialog1.OpenFile();
57                     TestXML a = (TestXML)xs.Deserialize(s);
58                     textBox1.Text = a.name;
59                     textBox2.Text = a.age;
60                     textBox3.Text = a.sex;
61                     s.Close();
62                 }
63                 catch (Exception ex)
64                 {
65                     MessageBox.Show(ex.Message);
66                 }
67             }
68         }
69     }
70 }
71 
原文地址:https://www.cnblogs.com/wbcms/p/1668629.html