公用類庫(5) Xml操作輔助類XmlUtil


  Xml操作輔助類主要包括兩大操作,Xml的序列化與反序列化。代碼如下:

namespace Tmac.Utilities
{
    /// <summary>
    /// Xml操作類
    /// </summary>
    public class XmlUtil
    {
        /// <summary>
        /// 序列化對象為xml(或字節流)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize(object obj)
        {
            string result = null;

            try
            {
                XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, new UTF8Encoding(false));
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlSerializer.Serialize(xmlTextWriter, obj);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    result = uTF8Encoding.GetString(stream.ToArray());
                }

            }
            catch (Exception ex)
            {
                throw new Exception("Couldn't serialize object:"+obj.GetType().Name,ex);
            }
            return result;
        }

        /// <summary>
        /// 反序列xml為對象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="type"></param>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(Type type,string xmlPath)
        { 
            T obj=default(T);

            XmlSerializer xmlSerializer = new XmlSerializer(type);
            try
            {
                using (StreamReader sr = new StreamReader(xmlPath))
                {
                    obj=(T)xmlSerializer.Deserialize(sr);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Couldn't parse xml:{0};Type:{1}",xmlPath,type.FullName), ex);
            }
            return obj;
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM