類為我們提供了自己對象串行化(Serialize)和反串行化(Deserialize)的XML的方法,該類可以序列化的內容:
公共類的公共讀寫字段或者屬性
XMLElement對象
XMLNode對象
Dataset對象
實現了Icollection 或IEnumerable的類
該類在設計中有一個設計需求:
需要被序列化的類要提供一個空參數的構造函數,否則運行時會出現異常.。
在開發過程中可能會有很多地方要用到對象和XML相互轉化,在此提供一個通用的類,提供泛類型的支持。
- /// <summary>
- /// 序列化幫助類
- /// </summary>
- public class SHelper
- {
- /// <summary>
- /// 對象到XML-----泛類型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obj"></param>
- /// <returns></returns>
- public static string SaveXMLFromObj<T>(T obj)
- {
- if (obj == null) return null;
- XMLSerializer serializer = new XMLSerializer(typeof(T));
- MemoryStream stream = new MemoryStream();
- XMLTextWriter xtw = new XMLTextWriter(stream, Encoding.UTF8);
- xtw.Formatting = Formatting.Indented;
- try
- {
- serializer.Serialize(stream, obj);
- }
- catch { return null; }
- stream.Position = 0;
- string returnStr = string.Empty;
- using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))
- {
- string line = "";
- while ((line = sr.ReadLine()) != null)
- {
- returnStr += line;
- }
- }
- return returnStr;
- }
- /// <summary>
- /// XML到反序列化到對象----支持泛類型
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="data"></param>
- /// <returns></returns>
- public static T LoadObjFromXML<T>(string data)
- {
- using (MemoryStream stream = new MemoryStream())
- {
- using (StreamWriter sw = new StreamWriter(stream, Encoding.UTF8))
- {
- sw.Write(data);
- sw.Flush();
- stream.Seek(0, SeekOrigin.Begin);
- XMLSerializer serializer = new XMLSerializer(typeof(T));
- try
- {
- return ((T)serializer.Deserialize(stream));
- }
- catch { return default(T); }
- }
- }
- }
- }
該類提供兩方法,一個是從實體到返回XML字符串的方法,一個是把XML字符串裝成對象實體的方法。下面我們來看看這個類是怎麼用的。
首先建兩個類USer和Users,User測試一個實體的序列化和反序列化,USers測試一個List集合序列化和反序列化。注意這兩個類都標注了[Serializable]特性,並且提供了空參數的構造函數。
- [Serializable]
- public class User
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string Add { get; set; }
- public int Age { get; set; }
- public User()
- {
- this.ID = default(int);
- this.Name = default(string);
- this.Add = default(string);
- this.Age = default(int);
- }}
- [Serializable]
- public class Users
- {
- public List<User> Datas
- { get; set; }
- public Users()
- { this.Datas=new List<User>();
- }
- }
下面我們建一個頁面Default.ASPx,在這個頁面中我們測試序列化,提供兩個按鈕和兩個TextBox,來分別顯示單個實體的序列化和List集合的序列化。
代碼
後台代碼的實現:
- <form id="form1" runat="server"> <div>
- <ASP:Button ID="Button1" runat="server" Text="一個對象序列化" onclick="Button1_Click" /> <br />
- <ASP:TextBox ID="TextBox1" runat="server" Width="100%" Height="200"></ASP:TextBox><br />
- <ASP:Button ID="Button2" runat="server" Text="多個對象序列化" onclick="Button2_Click" /><br />
- <ASP:TextBox ID="TextBox2" runat="server" Width="100%" Height="200">
- </ASP:TextBox><br /> </div> </form>
代碼
- /// <summary>
- /// 一個對象序列化
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param> protected void Button1_Click(object sender, EventArgs e)
- { User user = new User()
- { ID=1001,Name="小王",Add="北京",Age=21};
- var str = SHelper.SaveXMLFromObj<User>(user); this.TextBox1.Text = str; }
- /// <summary>
- /// 多個對象序列化
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param> protected void Button2_Click(object sender, EventArgs e)
- { Users users = new Users(); User user = new User()
- { ID = 1001, Name = "小王", Add = "北京", Age = 21 }; users.Datas.Add(user);
- users.Datas.Add(user);
- users.Datas.Add(user);
- var str = SHelper.SaveXMLFromObj<Users>(users); this.TextBox2.Text = str; }
序列化結果如下:
單對象:
- <?XML version="1.0"?>
- <User XMLns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- XMLns:xsd="http://www.w3.org/2001/XMLSchema"> <ID>1001</ID>
- <Name>小王</Name> <Add>北京</Add>
- <Age>21</Age></User>
List集合:
- <?XML version="1.0"?>
- <Users XMLns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- XMLns:xsd="http://www.w3.org/2001/XMLSchema"> <Datas> <User> <ID>1001</ID>
- <Name>小王</Name> <Add>北京</Add> <Age>21</Age> </User> <User> <ID>1001</ID>
- <Name>小王</Name>
- <Add>北京</Add> <Age>21</Age> </User> <User> <ID>1001</ID>
- <Name>小王</Name> <Add>北京</Add> <Age>21</Age> </User> </Datas></Users>
下面我們來測試反序列化:
首先建一個webservice,寫兩個測試方法:
代碼
- [WebMethod]
- public string GetObjFromXML(string data)
- { var obj = SHelper.LoadObjFromXML<User>(data);
- if (obj != null)
- { return obj.Name; }
- else
- { return "傳入數據出錯"; } }
- [WebMethod]
- public string GetObJSFromXML(string data)
- { var obj = SHelper.LoadObjFromXML<Users>(data);
- if (obj != null)
- { string returnstr = "";
- foreach (User user in obj.Datas)
- { returnstr += user.Name + "\n"; }
- return returnstr; }
- else { return "傳入數據出錯"; }
- }
編譯後運行,我們用剛才序列化出來的字符串貼出參數值位置就可以測試反序列化的方法,在此不再詳述,有興趣的童鞋可以把實例代碼運行。