C# XML與對象互相轉換

來源:互聯網
上載者:User

標籤:

 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與對象互相轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.