標籤:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using System.Xml.Serialization; 5 using System.IO; 6 using System.Xml; 7 8 namespace Common 9 {10 public class XmlUtility11 {12 /// <summary>13 /// 將自訂對象序列化為XML字串14 /// </summary>15 /// <param name="myObject">自訂對象實體</param>16 /// <returns>序列化後的XML字串</returns>17 public static string SerializeToXml<T>(T myObject)18 {19 if (myObject != null)20 {21 XmlSerializer xs = new XmlSerializer(typeof(T));22 23 MemoryStream stream = new MemoryStream();24 XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);25 writer.Formatting = Formatting.None;//縮排26 xs.Serialize(writer, myObject);27 28 stream.Position = 0;29 StringBuilder sb = new StringBuilder();30 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))31 {32 string line;33 while ((line = reader.ReadLine()) != null)34 {35 sb.Append(line);36 }37 reader.Close();38 }39 writer.Close();40 return sb.ToString();41 }42 return string.Empty;43 }44 45 /// <summary>46 /// 將XML字串還原序列化為對象47 /// </summary>48 /// <typeparam name="T">物件類型</typeparam>49 /// <param name="xml">XML字元</param>50 /// <returns></returns>51 public static T DeserializeToObject<T>(string xml)52 {53 T myObject;54 XmlSerializer serializer = new XmlSerializer(typeof(T));55 StringReader reader = new StringReader(xml);56 myObject = (T)serializer.Deserialize(reader);57 reader.Close();58 return myObject;59 }60 }61 }
C# XML與對象互相轉換