对象的xml序列化、反序列化

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

namespace Demo026
{
    class Program
    {
        static void Main(string[] args)
        {

            var person = new Person() { Id = 1, Name = "这个测试" };
            var orders = new List<Order>()
                             {
                                 new Order() {Id = 1, PersonId = 1},
                                 new Order() {Id = 211, PersonId = 1},
                                 new Order() {Id = 3, PersonId = 1, OrderDate = DateTime.Today.AddMinutes(89)}
                             };
            person.Orders = orders;

            string result = ObjectHelper.XmlSerialize(person);

            Console.WriteLine(result);

            var test = ObjectHelper.XmlDeserialize<Person>(result);
            if (test != null)
            {
                Console.WriteLine(test.Name);
                Console.WriteLine(test.Orders[2].OrderDate.ToString("yyyy-MM-dd HH:mm:ss"));
            }

            Console.ReadKey();

        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Order> Orders { get; set; }

    }

    public class Order
    {
        public int Id { get; set; }
        public int PersonId { get; set; }
        public DateTime OrderDate { get; set; }
    }


    public class ObjectHelper
    {
        /// <summary>
        /// 将对象序列化为xml字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize<T>(T obj)
        {
            using (var writer = new StringWriter())
            {
                new XmlSerializer(obj.GetType()).Serialize((TextWriter)writer, obj);
                return writer.ToString();
            }

        }

        /// <summary>
        /// 将xml字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T XmlDeserialize<T>(string xml)
        {
            T result = default(T);
            if (!string.IsNullOrEmpty(serialObj))
            {
                using (StringReader reader = new StringReader(serialObj))
                {
                    var serializer = new XmlSerializer(typeof(T));
                    result = (T)serializer.Deserialize(reader);
                }
            }
            return result;

        }

    }

}

 

posted on 2011-08-01 09:35  HTTP500  阅读(165)  评论(0编辑  收藏  举报