zoukankan      html  css  js  c++  java
  • XML序列化与反序列化

    调用方式:

      // 1. 首先要创建或者得到一个数据对象
    Order order = GetOrderById(123);
    
    
    // 2. 用序列化的方法生成XML
    string xml = XmlHelper.XmlSerialize(order, Encoding.UTF8);
    
    
    // 3. 从XML读取数据并生成对象
    Order order2 = XmlHelper.XmlDeserialize<Order>(xml, Encoding.UTF8);

    实现类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;
    using System.IO;
    using System.Xml;
    
    // 此处代码来源于博客【在.net中读写config文件的各种方法】的示例代码
    // http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html
    
    namespace ZuHeYiLou
    {
    
        // 1. 首先要创建或者得到一个数据对象
    //Order order = GetOrderById(123);
    
    
    // 2. 用序列化的方法生成XML
    //string xml = XmlHelper.XmlSerialize(order, Encoding.UTF8);
    
    
    // 3. 从XML读取数据并生成对象
    //Order order2 = XmlHelper.XmlDeserialize<Order>(xml, Encoding.UTF8);
    
        public static class XmlHelper
        {
            private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
            {
                if (o == null)
                    throw new ArgumentNullException("o");
                if (encoding == null)
                    throw new ArgumentNullException("encoding");
    
                XmlSerializer serializer = new XmlSerializer(o.GetType());
    
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineChars = "
    ";
                settings.Encoding = encoding;
                settings.IndentChars = "    ";
    
                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    serializer.Serialize(writer, o);
                    writer.Close();
                }
            }
    
            /// <summary>
            /// 将一个对象序列化为XML字符串
            /// </summary>
            /// <param name="o">要序列化的对象</param>
            /// <param name="encoding">编码方式</param>
            /// <returns>序列化产生的XML字符串</returns>
            public static string XmlSerialize(object o, Encoding encoding)
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    XmlSerializeInternal(stream, o, encoding);
    
                    stream.Position = 0;
                    using (StreamReader reader = new StreamReader(stream, encoding))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
    
            /// <summary>
            /// 将一个对象按XML序列化的方式写入到一个文件
            /// </summary>
            /// <param name="o">要序列化的对象</param>
            /// <param name="path">保存文件路径</param>
            /// <param name="encoding">编码方式</param>
            public static void XmlSerializeToFile(object o, string path, Encoding encoding)
            {
                if (string.IsNullOrEmpty(path))
                    throw new ArgumentNullException("path");
    
                using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    XmlSerializeInternal(file, o, encoding);
                }
            }
    
            /// <summary>
            /// 从XML字符串中反序列化对象
            /// </summary>
            /// <typeparam name="T">结果对象类型</typeparam>
            /// <param name="s">包含对象的XML字符串</param>
            /// <param name="encoding">编码方式</param>
            /// <returns>反序列化得到的对象</returns>
            public static T XmlDeserialize<T>(string s, Encoding encoding)
            {
                if (string.IsNullOrEmpty(s))
                    throw new ArgumentNullException("s");
                if (encoding == null)
                    throw new ArgumentNullException("encoding");
    
                XmlSerializer mySerializer = new XmlSerializer(typeof(T));
                using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
                {
                    using (StreamReader sr = new StreamReader(ms, encoding))
                    {
                        return (T)mySerializer.Deserialize(sr);
                    }
                }
            }
    
            /// <summary>
            /// 读入一个文件,并按XML的方式反序列化对象。
            /// </summary>
            /// <typeparam name="T">结果对象类型</typeparam>
            /// <param name="path">文件路径</param>
            /// <param name="encoding">编码方式</param>
            /// <returns>反序列化得到的对象</returns>
            public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
            {
                if (string.IsNullOrEmpty(path))
                    throw new ArgumentNullException("path");
                if (encoding == null)
                    throw new ArgumentNullException("encoding");
    
                string xml = File.ReadAllText(path, encoding);
                return XmlDeserialize<T>(xml, encoding);
            }
        }
    }
  • 相关阅读:
    [打印管理器]读取样式列表失败:Invalid variant operation
    分销产品安装在Win7系统上,日期格式错误的解决方案
    如何查看IIS与MSSQL数据库连接池
    分销研发部博客园正式开通了,欢迎大家关注
    asp.net Application_start()方法无法命中断点
    程序健壮性之“异常处理”
    解决问题--在Excel中使用条码字体打印出的code128条码不能被识别
    程序中的数据精度处理问题
    Spring.NET 学习笔记
    ASP.Net MVC开发基础学习笔记(1):走向MVC模式
  • 原文地址:https://www.cnblogs.com/tylertang/p/3214329.html
Copyright © 2011-2022 走看看