xml序列化與反序列化
一.概述
序列化是將一個對象(object)轉換成容易傳輸的形式,可以理解成解釋。反序列化的過程正好相反。例如在客戶端和服務器端需要傳輸一個object對象,那麼就可以在服務器端將這個對象先序列化成流形式,在傳遞給客戶端,客戶端在接收到流後,在進行反序列化的過程,重構object。
xml序列化只能轉換public成員(字段)和可讀寫屬性,不可以轉換方法,索引,私有成員(字段)或者只讀屬性。所以爲了序列化object所有的public或者private成員,方法和屬性,可以使用DataContractSerializer來代替XML序列化。這節內容就不講DataContractSerializer了。
二.舉例說明
這裏我只舉例說明如何轉換類對象,需要注意的是隻能轉換public object。
首先是Person類,就是我們需要序列化與反序列化的對象,是一個public類。
public class Person
{
public Person(){}
public Person(string name, int age, string job)
{
this.name = name;
this.age = age;
this.job = job;
}
public string name;
public int age;
private string job;
public string GetJob() { return job; }
}
然後是序列化與反序列化操作。先構建XmlSerializer對象,然後藉助該對象的Serialize方法和Deserialize方法進行序列化與反序列化。
static void SerializationPerson(string file)
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
TextWriter writer = new StreamWriter(file);
Person twj = new Person("唐維娟", 25, "建築師");
serializer.Serialize(writer, twj);
writer.Close();
}
static void DeserializationPerson(string file)
{
XmlSerializer serializer = new XmlSerializer(typeof(Person));
FileStream fs = new FileStream(file, FileMode.Open);
Person twj = new Person();
twj = (Person)serializer.Deserialize(fs);
Console.WriteLine("姓名:" + twj.name);
Console.WriteLine("年齡:" + twj.age);
Console.WriteLine("職業:" + twj.GetJob());
}
調用執行:
static void Main(string[] args)
{
SerializationPerson("C:/Users/a/Desktop/test.txt");
DeserializationPerson("C:/Users/a/Desktop/test.txt");
}
下面是結果:
從結果中可以看出,Person的私有成員job並沒有被序列化,從而造成數據丟失。如果想要序列化私有成員,需要使用DataContractSerializer。
xml序列化,不僅能序列化類對象,還可以序列化DataSet,XmlElement和XmlNode等等,如果想進一步學習可以參考微軟官方文檔。