探讨:使用XMLSerialize 序列化与反序列化


Posted in PHP onJune 08, 2013

概念:XML序列化是将公共字段和属性转化为序列格式(这里指XML),以便存储或传输的过程。反序列化则是从XML中重新创建原始状态的对象.

    class SerializeDemo
    {
        static void Main()
        {
            EmployeeCollection employeeCollection = new EmployeeCollection()
            {
                Employees = Employeer.Employees()
            };
            XmlSerializer serialize = new XmlSerializer(typeof(EmployeeCollection));
            string filePath = @"E:\PProject\Test\Employee.xml";
             SerializeEmployee(serialize, filePath, employeeCollection);
            DeserializeEmployee(serialize, filePath);
        }
        static void SerializeEmployee(XmlSerializer serialize, string filePath, EmployeeCollection employeeCollection)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                serialize.Serialize(fs, employeeCollection);
            }
        }
        static void DeserializeEmployee(XmlSerializer serialize,string filePath)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                EmployeeCollection collection = (EmployeeCollection)serialize.Deserialize(fs);
                collection.Employees.ForEach(e => Console.WriteLine("Name:{0},Gender:{1},Age:{2},Education:{3}", e.userName, e.gender, e.age, e.education));
            }
        }
    }
    [Serializable]
    public class EmployeeCollection
    {
        public List<Employeer> Employees { get; set; }
    }
    [Serializable]
    public class Employeer
    {
        public string userId { get; set; }
        public string userName { get; set; }
        public string gender { get; set; }
        public int age { get; set; }
        public List<WorkExperience> workExperience { get; set; }
        public string education { get; set; }
        public static List<Employeer> Employees()
        {
           return new List<Employeer>()
           {
                new Employeer() 
                {   
                    userId = "0001",
                    userName = "guoHu",
                    gender="Man",
                    age=25,education="underGraduate",
                    workExperience = WorkExperience.GetWorkExperience("0001")
                }
           };        }
    }
    [Serializable]
    public class WorkExperience
    {
        public string userId { get; set; }
        public string companyName { get; set; }
        public string seniority { get; set; }
        public static List<WorkExperience> GetWorkExperience(string userId)
        {
            List<WorkExperience> workExperience = new List<WorkExperience>();
            Unity unity = Unity.GetInstance();
            DataTable table = new DataTable();
            unity.GetTable(out table);
            var experiences = (from experience in table.AsEnumerable()
                               where experience.Field<string>("UserId") == userId
                               select new
                               {
                                   companyName = experience.Field<string>("CompanyName"),
                                   seniority = experience.Field<string>("Seniority")
                               }).ToList();
            experiences.ForEach(e => workExperience.Add(new WorkExperience() { companyName = e.companyName, seniority = e.seniority }));
            return workExperience;
        }
    }
    public class Unity
    {
        public static DataTable tables = new DataTable();
        public static DataRow dr;
        public static DataColumn dc = new DataColumn();
        public static object objLock = new object();
        public static Unity unityInstance;
        private Unity()
        {
        }
        public static Unity GetInstance()
        {
            if (unityInstance == null)
            {
                lock (objLock)
                {
                    if (unityInstance == null)
                    {
                        unityInstance = new Unity();
                    }
                }
            }
            return unityInstance;
        }
        public void GetTable(out DataTable dt)
        {
            unityInstance.CreateTable();
            dr = tables.NewRow();
            dr["UserId"] = "0001";
            dr["CompanyName"] = "WireSoft";
            dr["Seniority"] = "2012.02-2012.05";
            tables.Rows.Add(dr);
            dr = tables.NewRow();
            dr["UserId"] = "0001";
            dr["CompanyName"] = "Jin Xun";
            dr["Seniority"] = "2009.07-2011.02";
            tables.Rows.Add(dr);
            dr = tables.NewRow();
            dr["UserId"] = "0002";
            dr["CompanyName"] = "Hua Wei";
            dr["Seniority"] = "2011.07-";
            tables.Rows.Add(dr);
            dt = tables.Copy();
        }
        public  void CreateTable()
        {
            dc = new DataColumn("UserId", System.Type.GetType("System.String"));
            tables.Columns.Add(dc);
            dc = new DataColumn("companyName", System.Type.GetType("System.String"));
            tables.Columns.Add(dc);
            dc = new DataColumn("seniority", System.Type.GetType("System.String"));
            tables.Columns.Add(dc);
        }
    }

PHP 相关文章推荐
WML,Apache,和 PHP 的介绍
Oct 09 PHP
MYSQL数据库初学者使用指南
Nov 16 PHP
php strlen mb_strlen计算中英文混排字符串长度
Jul 10 PHP
PHP session有效期session.gc_maxlifetime
Apr 20 PHP
浅谈php中mysql与mysqli的区别分析
Jun 10 PHP
PHP文件上传主要代码讲解
Sep 30 PHP
php 获取SWF动画截图示例代码
Feb 10 PHP
Thinkphp中import的几个用法详细介绍
Jul 02 PHP
PHP将回调函数作用到给定数组单元的方法
Aug 19 PHP
PHP实现的带超时功能get_headers函数
Feb 10 PHP
PHP实现QQ登录的开原理和实现过程
Feb 04 PHP
php+mysql实现的无限分类方法类定义与使用示例
May 27 PHP
解析PHP自带的进位制之间的转换函数
Jun 08 #PHP
深入PHP内存相关的功能特性详解
Jun 08 #PHP
PHP rawurlencode与urlencode函数的深入分析
Jun 08 #PHP
PHP跳转页面的几种实现方法详解
Jun 08 #PHP
利用php递归实现无限分类 格式化数组的详解
Jun 08 #PHP
如何利用php array_multisort函数 对数据库结果进行复杂排序
Jun 08 #PHP
php引用返回与取消引用的详解
Jun 08 #PHP
You might like
PHP获取指定函数定义在哪个文件中以及其所在的行号实例
2014/05/08 PHP
Laravel 5框架学习之数据库迁移(Migrations)
2015/04/08 PHP
php安装dblib扩展,连接mssql的具体步骤
2017/03/02 PHP
PHP实现的简单sha1加密功能示例
2017/08/27 PHP
PHP 代码简洁之道(小结)
2019/10/16 PHP
很酷的javascript loading效果代码
2008/06/18 Javascript
常用简易JavaScript函数
2009/04/09 Javascript
jquery 关键字“拖曳搜索”之“拖曳”以及 图片“提示自适应放大”效果 的实现
2010/04/18 Javascript
IE6下通过a标签点击切换图片的问题
2010/11/14 Javascript
JavaScript排序算法之希尔排序的2个实例
2014/04/04 Javascript
jQuery中removeClass()方法用法实例
2015/01/05 Javascript
JS中artdialog弹出框控件之提交表单思路详解
2016/04/18 Javascript
用jquery快速解决IE输入框不能输入的问题
2016/10/04 Javascript
javascript加载xml 并解析各节点的值(实现方法)
2016/10/12 Javascript
使用vue构建移动应用实战代码
2017/08/02 Javascript
VUE Error: getaddrinfo ENOTFOUND localhost
2018/05/03 Javascript
微信小程序dom操作的替代思路实例分析
2018/12/06 Javascript
vue-week-picker实现支持按周切换的日历
2019/06/26 Javascript
vue跳转方式(打开新页面)及传参操作示例
2020/01/26 Javascript
python实现excel读写数据
2021/03/02 Python
Django model序列化为json的方法示例
2018/10/16 Python
解决pandas.DataFrame.fillna 填充Nan失败的问题
2018/11/06 Python
python实现简单的五子棋游戏
2020/09/01 Python
python 写一个性能测试工具(一)
2020/10/24 Python
matplotlib部件之矩形选区(RectangleSelector)的实现
2021/02/01 Python
关于box-sizing的全面理解
2016/07/28 HTML / CSS
html5教程画矩形代码分享
2013/12/04 HTML / CSS
Hotels.com日本:国外和海外住宿,酒店预订
2019/12/13 全球购物
会议邀请函范文
2014/01/09 职场文书
优秀党员主要事迹
2014/01/19 职场文书
产品设计开发计划书
2014/05/07 职场文书
2014年专项整治工作总结
2014/11/17 职场文书
预备党员个人总结
2015/02/14 职场文书
2015年乡镇纪检工作总结
2015/04/22 职场文书
2019年大学毕业生个人自我鉴定范文大全
2019/03/21 职场文书
Rust中的Struct使用示例详解
2022/08/14 Javascript