C#的StringWriter,XmlSerializer將對象等序列化為Xml字串

來源:互聯網
上載者:User

主要方法:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; namespace ConsoleApplication2 {     public class SimpleSerializer     {         /**//// <summary>         /// 序列化對象         /// </summary>         /// <typeparam name=\"T\">物件類型</typeparam>         /// <param name=\"t\">對象</param>         /// <returns></returns>         public static string Serialize<T>(T t) {             using (StringWriter sw = new StringWriter()) {                 XmlSerializer xz = new XmlSerializer(t.GetType());                 xz.Serialize(sw, t);                 return sw.ToString();             }         }                  /**//// <summary>         /// 還原序列化為對象         /// </summary>         /// <param name=\"type\">物件類型</param>         /// <param name=\"s\">對象序列化後的Xml字串</param>         /// <returns></returns>         public static object Deserialize(Type type, string s) {             using(StringReader sr = new StringReader(s)) { [Page]                XmlSerializer xz = new XmlSerializer(type);                 return xz.Deserialize(sr);             }         }     } } 

定義一個用於測試的實體類: 

 public class TestClass    {        public string MyFeild        {            get;            set;        }    }

測試:

 

 static void Main(string[] args)        {            TestClass x = new TestClass();            x.MyFeild = "測試";            using (StringWriter sw = new StringWriter())            {                XmlSerializer xz = new XmlSerializer(x.GetType());                xz.Serialize(sw, x);                Console.WriteLine(sw.ToString());                using (StringReader sr = new StringReader(sw.ToString()))                {                    Console.Write(((TestClass)xz.Deserialize(sr)).MyFeild);                }                Console.Read();            }        }

序列化的時候,各個欄位還有下面這類屬性,下次再寫  

[XmlElement("MyFeild")]public string MyFeild  {            get;            set;        }

 

參考資料:http://www.zxbc.cn/html/20080126/31552.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.