当前位置:  编程技术>.net/c#/asp.net

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

    来源: 互联网  发布时间:2014-10-29

    本文导语:  代码如下: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文本通用解释器    /// ...

代码如下:

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("]", 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!");
        }

    }
}


    
 
 

您可能感兴趣的文章:

  • Python namedtuple对象json序列化/反序列化及对象恢复
  • 序列化反序列化库 RedCell
  • java将类序列化并存储到mysql(使用hibernate)
  • 对象序列化--存储数据库的方法 序列化后 不能使用
  • java序列化实现Serializable接口
  • java 基本类型或可序列化类型,这里说的可序列化类型是什么意思???具体都有哪些类型??谢谢
  • C序列化或反序列化库 tpl
  • c#序列化和反序列化Json的方法
  • .net实现序列化与反序列化实例解析
  • 使用XmlSerializer序列化List对象成XML格式(list对象序列化)
  • java序列化和java反序列化示例
  • C#中datatable序列化与反序列化实例分析
  • Java对象序列化和反序列化工具 Xson
  • 轻量级的序列化/反序列化工具 XBlink
  • c#数据的序列化和反序列化(推荐版)
  • Java 序列化库 JID
  • C#实现json的序列化和反序列化实例代码
  • 关于object序列化的问题
  • 数据序列化系统 Apache Avro
  • 请教java在序列化时的中文问题?
  • C++序列化框架 febird
  • c#泛型序列化对象为字节数组的示例
  • C#实现复杂XML的序列化与反序列化
  • C#序列化与反序列化的实例详解
  • C# 三种序列化方法分享
  • c#保存窗口位置大小操作类(序列化和文件读写功能)
  • 深入理解C#序列化与反序列化的详解
  • c#序列化实例详解
  • C#实现简单的JSON序列化功能代码实例
  • c#对象反序列化与对象序列化示例详解
  • c#序列化详解示例
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • 深入理解Java对象的序列化与反序列化的应用
  • Java对象序列化框架 Kryo
  • Java序列化类库 protostuff
  • 不管你高低,只要能帮助我就谢谢 。如何对字符数组进行序列化
  • 在java中如何序列化
  • 谁知道Bean中的序列化(implements Serializable)的用处,及如何用?
  • 序列化协议 Spearal
  • Java 快速序列化库 FST
  • 请问:能不能动态的运行时生成对象(动态定义对象), 要涉及到哪些技术, 反射,序列化...??
  • Json序列化和反序列化方法解析
  • 探讨JQUERY JSON的反序列化类 using问题的解决方法
  • JSON反序列化库 Upida
  • 关于对象序列化的一个问题,如何从服务器向端客户端传记录集???
  • jquery序列化表单以及回调函数的使用示例
  • java对象序列化与反序列化的默认格式和json格式使用示例
  • 怎么能让序列化同步??
  • jquery序列化表单去除指定元素示例代码
  • 怎样实现对象的序列化
  • J2SE中的序列化的认识
  • 能不能将对象序列化后存到数据库再取出还原?有没有例子?


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3