代码改变世界

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

2012-06-14 11:01  音乐让我说  阅读(602)  评论(0编辑  收藏  举报

我的前一篇:  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 下载:https://files.cnblogs.com/Music/XmlHelper_XmlSerializer_Demo.rar

 

谢谢浏览!