zoukankan      html  css  js  c++  java
  • 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;
                }
            }
        }
    }
  • 相关阅读:
    amaze(妹子~) 好像挺好玩
    php 获取图片base64编码格式数据
    一些laravel博文
    微信移动端(wap)开发调试工具
    深入理解控制反转(IoC)和依赖注入(DI)
    使用 composer 下载更新卸载类库
    ionic ui 框架
    laravel 添加 404 页面
    laravel 调试模式及日志配置
    iOS-方法之+ initialize 与 +load
  • 原文地址:https://www.cnblogs.com/zhouzhaokun/p/3571981.html
Copyright © 2011-2022 走看看