关于XML序列化的简单例子:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//选择保存路径
private void button1_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "XML文件|*.xml";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
textBox1.Text=saveFileDialog1.FileName;
}
//将类序列化到XML文件
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
return;
mydata newdata = new mydata();
newdata.myname = "小明";
newdata.mybirthday = "09-31";
newdata.age = 23;
newdata.imageByte = Encoding.Default.GetBytes("999adfklasdjfl".ToCharArray());
XmlSerializer es=new XmlSerializer(typeof(mydata));
TextWriter writer = new StreamWriter(textBox1.Text);
es.Serialize(writer, newdata);
writer.Close();
}
//反序列化XML文件为类
private void button3_Click(object sender, EventArgs e)
{
XmlSerializer sd = new XmlSerializer(typeof(mydata));
TextReader drr = new StreamReader(textBox1.Text);
mydata mm;
mm = (mydata)sd.Deserialize(drr);
MessageBox.Show("mm.Name="+mm.myname+"/r/n"+
"mm.bothday=" + mm.mybirthday + "/r/n" +
"mm.age="+mm.age+"/r/n"+
"mm.imageByte="+Encoding.Default.GetString(mm.imageByte));
}
}
//the class to serializer
public class mydata
{
public string myname;
public string mybirthday;
public int age;
public byte[] imageByte;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//选择保存路径
private void button1_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "XML文件|*.xml";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
textBox1.Text=saveFileDialog1.FileName;
}
//将类序列化到XML文件
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
return;
mydata newdata = new mydata();
newdata.myname = "小明";
newdata.mybirthday = "09-31";
newdata.age = 23;
newdata.imageByte = Encoding.Default.GetBytes("999adfklasdjfl".ToCharArray());
XmlSerializer es=new XmlSerializer(typeof(mydata));
TextWriter writer = new StreamWriter(textBox1.Text);
es.Serialize(writer, newdata);
writer.Close();
}
//反序列化XML文件为类
private void button3_Click(object sender, EventArgs e)
{
XmlSerializer sd = new XmlSerializer(typeof(mydata));
TextReader drr = new StreamReader(textBox1.Text);
mydata mm;
mm = (mydata)sd.Deserialize(drr);
MessageBox.Show("mm.Name="+mm.myname+"/r/n"+
"mm.bothday=" + mm.mybirthday + "/r/n" +
"mm.age="+mm.age+"/r/n"+
"mm.imageByte="+Encoding.Default.GetString(mm.imageByte));
}
}
//the class to serializer
public class mydata
{
public string myname;
public string mybirthday;
public int age;
public byte[] imageByte;
}