.Net 序列化 及 反序列化 轉為 XML .Net 序列化 及 反序列化 轉為 XML
  .NET       ez      2012-11-11

首先加入Function

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        static T DoDeserialize<T>(string s)
        {
            XmlDocument XD = new XmlDocument();
            try
            {
                XD.LoadXml(s);
                XmlNodeReader XNR = new XmlNodeReader(XD.DocumentElement);
                XmlSerializer XS = new XmlSerializer(typeof(T));
                object obj = XS.Deserialize(XNR);
                return (T)obj;
            }
            catch
            {
                return default(T);
            }
        }
        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        static string DoSerialize(object o)
        {
            XmlSerializer XS = new XmlSerializer(o.GetType());
            StringBuilder SB = new StringBuilder();
            StringWriter SW = new StringWriter(SB);
            XS.Serialize(SW, o);
            return SB.ToString();
        }

使用方式,只需將 Object 帶入 DoSerialize 即可序列化,反序列化只需帶入 DoDeserialize:

//序列化
string Str = "測試";
string temp = DoSerialize(Str);
//反序列化
string temp = DoDeserialize<string>(temp);

標籤:   .NET

我要留言