using System.Runtime.Serialization;//.NET FrameWork3.0以上 //序列化 与反序列化 public string Serialize<T>(T data) //序列化 { using (var memoryStream = new MemoryStream()) { var serializer = new DataContractSerializer(typeof(T)); serializer.WriteObject(memoryStream, data); memoryStream.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(memoryStream); string content = reader.ReadToEnd(); return content; } } public T Deserialize<T>(string xml)//反序化 { using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(xml))) { var serializer = new DataContractSerializer(typeof(T)); T theObject = (T)serializer.ReadObject(stream); return theObject; } } [Serializable] [XmlRoot(ElementName = "Pupil", Namespace = "urn:MyNamespace")] public class Employee { private string[] employeeInfo; [XmlElement] public int EmployeeID; [XmlElement] public string EmployeeName; [XmlElement] public string[] EmployeeInfo { get { return this.employeeInfo; } set { this.employeeInfo = value; } } } //由于是序列化和反序化是泛型,当添加单个实例的时候; Employee ep = new Employee { EmployeeID = 100, EmployeeName = "Daqing", EmployeeInfo =new string[]{ "we", "are" } }; Serialize(ep); //添加list<T>的时候同理 IList<Employee> lem = new List<Employee>(); for(int k=0;k<3;k++) { ep=new Employee(); ep.EmployeeID=k; ep.EmployeeInfo=new string[]{k.ToString()}; ep.EmployeeName="Daqing"+k.ToString(); lem.Add(ep); } Serialize(lem ); //下面还有一种方法,采用XmlSerializer串行化,该方法需要的命名空间 Using System.Xml.Serialization /// <summary> /// 序列化成xml字符串 /// </summary> /// <param name="obj"></param> /// <returns>序列化后的字符串</returns> public string Serialize(object obj) { XmlSerializer xs = new XmlSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8); xtw.Formatting = System.Xml.Formatting.Indented; xs.Serialize(xtw, obj); ms.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(ms)) { string str = sr.ReadToEnd(); xtw.Close(); ms.Close(); return str; } } } public T Deserialize<T>(string xml) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml))) { var serializer = new DataContractSerializer(typeof(T)); T theObject = (T)serializer.ReadObject(stream); return theObject; } } /// <summary> /// 反序列化方法 /// </summary> /// <param name="xml">xml字符串</param> /// <param name="type">反序列化对象的类型</param> /// <returns>反序列化后的对象</returns> public object Desrialize(string xml, Type type) { object obj = null; XmlSerializer xs = new XmlSerializer(type); TextReader tr; if (!File.Exists(xml)) { tr = new StringReader(xml); } else { tr = new StreamReader(xml); } using (tr) { obj = xs.Deserialize(tr); } return obj; }