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

{

    ///


    /// XML文本通用解释器

    ///


    public class XmlHelper

    {

        private const string EncodePattern = "<[^>]+?encoding="(?[^<>\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 Parsers = new Dictionary();

        #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;

        }

        ///


        /// 解析XML文件

        ///


        /// 类型

        /// 文件名

        /// 类的实例

        public T ParseFile(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().Replace("-", "") + ".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(body, enc);

        }

        ///


        /// 将对象序列化为XML文件

        ///


        /// 文件名

        /// 对象

        ///

        /// 文件名错误异常

        public bool SaveFile(string fileName, object obj)

        {

            return SaveFile(fileName, obj, DefEncoding);

        }

        ///


        /// 将对象序列化为XML文件

        ///


        /// 文件名

        /// 对象

        ///

        ///

        /// 文件名错误异常

        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;

        }

        ///


        /// 解析文本

        ///


        /// 需要解析的类

        /// 待解析文本

        /// 类的实例

        public T Parse(string body) where T : class, new()

        {

            var encoding = GetEncoding(body);

            return Parse(body, encoding);

        }

        ///


        /// 解析文本

        ///


        /// 需要解析的类

        /// 待解析文本

        ///

        /// 类的实例

        public T Parse(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 + "ttroot:" + 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);

            }

        }

        ///


        /// 解析未知类型的XML内容

        ///


        /// Xml文本

        /// 字符编码

        ///

        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;

        }

        ///


        /// 用XML序列化对象

        ///


        ///

        ///

        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

        ///


        /// 获取XML响应的根节点名称

        ///


        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!");

        }

    }

}

0.215493s