C# 中的序列化与反序列化(二)

我的前一篇:  C# 中的序列化与反序列化

直接贴代码了:

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

namespace RwConfigDemo
{
    public static class XmlHelper
    {
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            byte[] bytes = XmlSerializeInternal(o, encoding);
            return encoding.GetString(bytes);
        }

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

            byte[] bytes = XmlSerializeInternal(o, encoding);
            File.WriteAllBytes(path, bytes);
        }

        /// <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);
        }

        private static byte[] XmlSerializeInternal(object o, Encoding encoding)
        {
            if (o == null)
                throw new ArgumentNullException("o");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            XmlSerializer ser = new XmlSerializer(o.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlTextWriter writer = new XmlTextWriter(ms, encoding))
                {
                    writer.Formatting = Formatting.Indented;
                    ser.Serialize(writer, o);
                    writer.Close();
                }
                return ms.ToArray();
            }
        }
    }
}

 

代码来源于博客【在.net中读写config文件的各种方法】的示例代码 http://www.cnblogs.com/fish-li/archive/2011/12/18/2292037.html

我的测试代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using RwConfigDemo;
using System.IO;

namespace FormsAuthClient
{
    class Program
    {
        static void Main(string[] args)
        {
            IList<Student> students = StudentRepository.GetAllStudents();
            string xmlString = XmlHelper.XmlSerialize(students, Encoding.UTF8);
            Console.WriteLine(xmlString);
            string xmlFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Guid.NewGuid() + ".xml");
            XmlHelper.XmlSerializeToFile(students, xmlFileName, Encoding.UTF8);

            Student[] studentsFromXmlDeserialize = XmlHelper.XmlDeserialize<Student[]>(xmlString, Encoding.UTF8);
            // 注意这里不能反序列化为 IList<Student>,可以序列化为 Student[]、List<Student>,否则会抛出异常:
            // 不能序列化接口 IList<Student>
            ShowStudent(studentsFromXmlDeserialize);
            Console.WriteLine("===================================");
            List<Student> studentsXmlDeserializeFromFile = XmlHelper.XmlDeserializeFromFile<List<Student>>(xmlFileName, Encoding.UTF8);
            ShowStudent(studentsXmlDeserializeFromFile);
        }

        static void ShowStudent(IEnumerable<Student> items)
        {
            foreach (Student item in items)
            {
                Console.WriteLine("ID:" + item.Id + ", Name:" + item.Name + ",DateOfBirth:" + item.DateOfBirth);
            }
        }
    }

    public class StudentRepository
    {
        public static IList<Student> GetAllStudents()
        {
            return new Student[]
            {
                new Student(){ Id = 1, Name = "张三", DateOfBirth = new DateTime(1985,8,3) },
                new Student(){ Id = 2, Name = "李四", DateOfBirth = new DateTime(1986,9,3) },
                new Student(){ Id = 3, Name = "王武", DateOfBirth = new DateTime(1987,10,3) },
                new Student(){ Id = 4, Name = "赵六", DateOfBirth = new DateTime(1988,11,3) }
            };
        }
    }

    public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public DateTime DateOfBirth { get; set; }
    }
}

 

测试结果截图:

 

序列化产生的 Xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfStudent xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Student>
    <Id>1</Id>
    <Name>张三</Name>
    <DateOfBirth>1985-08-03T00:00:00</DateOfBirth>
  </Student>
  <Student>
    <Id>2</Id>
    <Name>李四</Name>
    <DateOfBirth>1986-09-03T00:00:00</DateOfBirth>
  </Student>
  <Student>
    <Id>3</Id>
    <Name>王武</Name>
    <DateOfBirth>1987-10-03T00:00:00</DateOfBirth>
  </Student>
  <Student>
    <Id>4</Id>
    <Name>赵六</Name>
    <DateOfBirth>1988-11-03T00:00:00</DateOfBirth>
  </Student>
</ArrayOfStudent>

 

Demo 下载:http://files.cnblogs.com/Music/XmlHelper_XmlSerializer_Demo.rar

 

谢谢浏览!

 

转载于:https://www.cnblogs.com/Music/archive/2012/06/14/about-c-sharp-serialize-and-deserialize-2.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值