• C# 序列化高级用法


    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;
                }
            }
        }
    }
  • 相关阅读:
    PythonStudy——greenlet 协程
    PythonStudy——事件 Event
    PythonStudy——单线程并发的实现
    2015年的总结
    kylin一种OLAP的实现
    分布式消息队列的使用kakfa
    第一次听到了docker
    Hive分布式的数据仓库
    dubbo服务框架学习
    Storm实时计算框架的编程模式
  • 原文地址:https://www.cnblogs.com/zhouzhaokun/p/3571981.html
Copyright © 2020-2023  润新知