首页 > 其他 > 详细

C# 序列化高级用法

时间:2014-02-28 10:34:07      阅读:304      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var model = new Person() { ID = 1, Name = "Eric", Age = 26, Address = "15F" };

            string xml = ObjectXmlSerializer.Serialize<Person>(model);
            xml = System.Text.RegularExpressions.Regex.Replace(xml, "^<\\?.+\\?>", string.Empty);
            Console.WriteLine(xml);
            Console.ReadLine();
        }
    }

    [Serializable]
    [XmlRoot(Namespace = "http://newegg.com/xml")]
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }

    public class ObjectXmlSerializer
    {
        public static string Serialize<T>(T t)
        {
            StringBuilder sb = new StringBuilder();
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            using (TextWriter writer = new StringWriter(sb))
            {
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("", "http://newegg.com/xml");
                xmlSer.Serialize(writer, t, namespaces);
                return writer.ToString();
            }

        }

        public static T Deserialize<T>(string str)
        {
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            using (TextReader reader = new StringReader(str))
            {
                T t = (T)xmlSer.Deserialize(reader);
                return t;
            }
        }
    }
}
bubuko.com,布布扣

C# 序列化高级用法,布布扣,bubuko.com

C# 序列化高级用法

原文:http://www.cnblogs.com/zhouzhaokun/p/3571981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!