XML和實體類之間相互轉換(序列化和反序列化)
XML文件與實體類的互相轉換
通過我前面的幾篇收藏的文章,今天來自己做個對實體類對象序列化和反序列化的匯總,以下代碼是經過上面文章的參考,然后稍加改動。
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Xml.Serialization; namespace CarWash.Station.Comm { public class XmlUtil { //序列化 //接收4個參數:srcObject(對象的實例),type(對象類型),xmlFilePath(序列化之后的xml文件的絕對路徑),xmlRootName(xml文件中根節點名稱) //當需要將多個對象實例序列化到同一個XML文件中的時候,xmlRootName就是所有對象共同的根節點名稱,如果不指定,.net會默認給一個名稱(ArrayOf+實體類名稱) public static string SerializeToXml(object obj, Type type=null) { string str = ""; if (obj != null) { type = type != null ? type : obj.GetType(); using (MemoryStream ms = new MemoryStream()) { using (StreamReader sr = new StreamReader(ms)) { XmlSerializer xs = new XmlSerializer(type); xs.Serialize(ms, obj); ms.Position = 0; str = sr.ReadToEnd(); } } } return str; } public static byte[] SerializeToStream(object obj, Type type) { byte[] result = null; if (obj != null) { type = type != null ? type : obj.GetType(); using (MemoryStream ms = new MemoryStream()) { ms.Position = 0; XmlSerializer xs = new XmlSerializer(type); xs.Serialize(ms, obj); result = ms.ToArray(); } } return result; } //反序列化 //接收2個參數:xmlFilePath(需要反序列化的XML文件的絕對路徑),type(反序列化XML為哪種對象類型) public static object DeserializeFromXml(string xml, Type type) { object result = null; if (!string.IsNullOrEmpty(xml)) { using (StringReader sr = new StringReader(xml)) { XmlSerializer xs = new XmlSerializer(type); result = xs.Deserialize(sr); } } return result; } /// <summary> /// 反序列化 /// </summary> /// <param name="type"></param> /// <param name="xml"></param> /// <returns></returns> public static object DeserializeFromStream(Stream stream, Type type) { object result = null; if (stream != null) { XmlSerializer xmldes = new XmlSerializer(type); result = xmldes.Deserialize(stream); } return result; } } }
使用方式和實例我就不介紹,可看前面的幾篇文章,他們都有比較詳細的說明。
以上文字純屬個人總結,全部手動輸入,如果引用請注明出處。