首頁 > 後端開發 > C#.Net教程 > C# xml序列化類別的程式碼實例詳解

C# xml序列化類別的程式碼實例詳解

黄舟
發布: 2017-03-03 11:49:15
原創
1568 人瀏覽過

C#  xml序列化類別的程式碼實例詳解

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Imps.Services.CommonV4;


namespace Imps.Services.IDCService.Utility
{
    public class XMLSerializerEx
    {
        private static ITracing _tracing = TracingManager.GetTracing("XMLSerializerEx");
        /// <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));


            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            namespaces.Add(string.Empty, string.Empty);
            
            MemoryStream stream = new MemoryStream();
            XmlTextWriter xtw = new XmlTextWriter(stream, Encoding.UTF8);
            xtw.Formatting = Formatting.Indented;
            try
            {
                serializer.Serialize(stream, obj,namespaces);
            }
            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;
        }




        public static T LoadObjFromXML<T>(Stream s)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            try
            {
                return ((T)serializer.Deserialize(s));
            }
            catch { return default(T); }
        }


        /// <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);
                    return LoadObjFromXML<T>(stream);


                }
            }
        }
        
    }
}
登入後複製

 以上就是C#  xml序列化類別的程式碼實例詳解的內容,更多相關內容請關注PHP中文網(www.php.cn)!


#
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板