Xml基础02
几种序列化方式和反序列化:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace day29test03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Person person = new Person();
person.Age = 20;
person.Name = "qew";
person.Height = 1777;
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
System.IO.TextWriter yw = new System.IO.StreamWriter(@"F:\.net学习\test\xmldeemp1\1.xml");
xmlSerializer.Serialize(yw, person);
yw.Dispose();
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
System.IO.MemoryStream ms = new System.IO.MemoryStream();
xmlSerializer.Serialize(ms, person);
byte[] ns = ms.GetBuffer();
String str = System.Text.Encoding.UTF8.GetString(ns);
MessageBox.Show(str);
}
private void button2_Click(object sender, EventArgs e)
{
System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
System.IO.TextReader tr = new System.IO.StreamReader(@"F:\.net学习\test\xmldeemp1\1.xml");
Person p = (Person)xmlSerializer.Deserialize(tr);
}
}
[System.Xml.Serialization.XmlRoot("mtxml", Namespace="www.nb.com")]
public class Person
{
private String name;
private int age;
private double height;
public string Name {
get => name; set => name = value; }
public int Age {
get => age; set => age = value; }
public double Height {
get => height; set => height = value; }
}
}