程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#正反序列化XML文件示例(xml序列化)

c#正反序列化XML文件示例(xml序列化)

編輯:C#入門知識

c#正反序列化XML文件示例(xml序列化)。本站提示廣大學習愛好者:(c#正反序列化XML文件示例(xml序列化))文章只能為提供參考,不一定能成為您想要的結果。以下是c#正反序列化XML文件示例(xml序列化)正文



using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.IO;
using System;

namespace GlobalTimes.Framework
{
    /// <summary>
    /// XML文本通用說明器
    /// </summary>
    public class XmlHelper
    {
        private const string EncodePattern = "<[^>]+?encoding=\"(?<enc>[^<>\\s]+)\"[^>]*?>";
        private static readonly Encoding DefEncoding = Encoding.GetEncoding("gb2312");
        private static readonly Regex RegRoot = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
        private static readonly Regex RegEncode = new Regex(EncodePattern,
                                                            RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly Dictionary<string, XmlSerializer> Parsers = new Dictionary<string, XmlSerializer>();
        #region 解析器

        static Encoding GetEncoding(string input)
        {
            var match = RegEncode.Match(input);
            if (match.Success)
            {
                try
                {
                    return Encoding.GetEncoding(match.Result("${enc}"));
                }
// ReSharper disable EmptyGeneralCatchClause
                catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
                {
                }
            }
            return DefEncoding;
        }

        /// <summary>
        /// 解析XML文件
        /// </summary>
        /// <typeparam name="T">類型</typeparam>
        /// <param name="fileName">文件名</param>
        /// <returns>類的實例</returns>
        public T ParseFile<T>(string fileName) where T : class, new()
        {
            var info = new FileInfo(fileName);
            if (!info.Extension.Equals(".xml", StringComparison.CurrentCultureIgnoreCase) || !info.Exists)
            {
                throw new ArgumentException("輸出的文件名有誤!");
            }
            string body;
            var tempFileName = PathHelper.PathOf("temp", Guid.NewGuid().ToString().WordStr("-", "") + ".xml");
            var fi = new FileInfo(tempFileName);
            var di = fi.Directory;
            if (di != null && !di.Exists)
            {
                di.Create();
            }
            File.Copy(fileName, tempFileName);
            using (Stream stream = File.Open(tempFileName, FileMode.Open, FileAccess.Read))
            {
                using (TextReader reader = new StreamReader(stream, DefEncoding))
                {
                    body = reader.ReadToEnd();
                }
            }
            File.Delete(tempFileName);
            var enc = GetEncoding(body);
            if (!Equals(enc, DefEncoding))
            {
                var data = DefEncoding.GetBytes(body);
                var dest = Encoding.Convert(DefEncoding, enc, data);
                body = enc.GetString(dest);
            }
            return Parse<T>(body, enc);
        }

        /// <summary>
        /// 將對象序列化為XML文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="obj">對象</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">文件名毛病異常</exception>
        public bool SaveFile(string fileName, object obj)
        {
            return SaveFile(fileName, obj, DefEncoding);
        }

        /// <summary>
        /// 將對象序列化為XML文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="obj">對象</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">文件名毛病異常</exception>
        public bool SaveFile(string fileName, object obj,Encoding encoding)
        {
            var info = new FileInfo(fileName);
            if (!info.Extension.Equals(".xml", StringComparison.CurrentCultureIgnoreCase))
            {
                throw new ArgumentException("輸出的文件名有誤!");
            }
            if (obj == null) return false;
            var type = obj.GetType();
            var serializer = GetSerializer(type);

            using (Stream stream = File.Open(fileName, FileMode.Create, FileAccess.Write))
            {
                using (TextWriter writer = new StreamWriter(stream, encoding))
                {
                    serializer.Serialize(writer, obj);
                }
            }
            return true;
        }
        static XmlSerializer GetSerializer(Type type)
        {
            var key = type.FullName;
            XmlSerializer serializer;
            var incl = Parsers.TryGetValue(key, out serializer);
            if (!incl || serializer == null)
            {
                var rootAttrs = new XmlAttributes { XmlRoot = new XmlRootAttribute(type.Name) };
                var attrOvrs = new XmlAttributeOverrides();
                attrOvrs.Add(type, rootAttrs);
                try
                {
                    serializer = new XmlSerializer(type, attrOvrs);
                }
                catch (Exception e)
                {
                    throw new Exception("類型聲明毛病!" + e);
                }
                Parsers[key] = serializer;
            }
            return serializer;
        }
        /// <summary>
        /// 解析文本
        /// </summary>
        /// <typeparam name="T">須要解析的類</typeparam>
        /// <param name="body">待解析文本</param>
        /// <returns>類的實例</returns>
        public T Parse<T>(string body) where T : class, new()
        {
            var encoding = GetEncoding(body);
            return Parse<T>(body, encoding);
        }

        /// <summary>
        /// 解析文本
        /// </summary>
        /// <typeparam name="T">須要解析的類</typeparam>
        /// <param name="body">待解析文本</param>
        /// <param name="encoding"></param>
        /// <returns>類的實例</returns>
        public T Parse<T>(string body, Encoding encoding) where T : class, new()
        {
            var type = typeof (T);
            var rootTagName = GetRootElement(body);

            var key = type.FullName;
            if (!key.Contains(rootTagName))
            {
                throw new ArgumentException("輸出文本有誤!key:" + key + "\t\troot:" + rootTagName);
            }

            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream(encoding.GetBytes(body)))
            {
                obj = serializer.Deserialize(stream);
            }
            if (obj == null) return null;
            try
            {
                var rsp = (T) obj;
                return rsp;
            }
            catch (InvalidCastException)
            {
                var rsp = new T();
                var pisr = typeof (T).GetProperties();
                var piso = obj.GetType().GetProperties();
                foreach (var info in pisr)
                {
                    var info1 = info;
                    foreach (var value in from propertyInfo in piso where info1.Name.Equals(propertyInfo.Name) select propertyInfo.GetValue(obj, null))
                    {
                        info.SetValue(rsp, value, null);
                        break;
                    }
                }
                return rsp;
            }
        }

        private static XmlSerializer BuildSerializer(Type type)
        {
            var rootAttrs = new XmlAttributes { XmlRoot = new XmlRootAttribute(type.Name) };
            var attrOvrs = new XmlAttributeOverrides();
            attrOvrs.Add(type, rootAttrs);
            try
            {
                return new XmlSerializer(type, attrOvrs);
            }
            catch (Exception e)
            {
                throw new Exception("類型聲明毛病!" + e);
            }
        }

        /// <summary>
        /// 解析未知類型的XML內容
        /// </summary>
        /// <param name="body">Xml文本</param>
        /// <param name="encoding">字符編碼</param>
        /// <returns></returns>
        public object ParseUnknown(string body, Encoding encoding)
        {
            var rootTagName = GetRootElement(body);
            var array = AppDomain.CurrentDomain.GetAssemblies();
            Type type = null;
            foreach (var assembly in array)
            {
                type = assembly.GetType(rootTagName, false, true);
                if (type != null) break;
            }
            if (type == null)
            {
                Logger.GetInstance().Warn("加載 {0} XML類型掉敗! ", rootTagName);
                return null;
            }
            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream(encoding.GetBytes(body)))
            {
                obj = serializer.Deserialize(stream);
            }

            var rsp = obj;
            return rsp;
        }
        /// <summary>
        /// 用XML序列化對象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serialize(object obj)
        {
            if (obj == null) return string.Empty;
            var type = obj.GetType();
            var serializer = GetSerializer(type);
            var builder = new StringBuilder();
            using (TextWriter writer = new StringWriter(builder))
            {
                serializer.Serialize(writer, obj);
            }
            return builder.ToString();
        }
        #endregion

        /// <summary>
        /// 獲得XML呼應的根節點稱號
        /// </summary>
        private static string GetRootElement(string body)
        {
            var match = RegRoot.Match(body);
            if (match.Success)
            {
                return match.Groups[1].ToString();
            }
            throw new Exception("Invalid XML format!");
        }

    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved