加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML文件系列三之序列化与反序列化

发布时间:2020-12-16 08:53:45 所属栏目:百科 来源:网络整理
导读:序列化是将对象转换为可保持或传输的格式的过程。反序列化的过程正好是相反的过程。 一、准备阶段,得有一个可供序列化的对象类Person类。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using

序列化是将对象转换为可保持或传输的格式的过程。反序列化的过程正好是相反的过程。
一、准备阶段,得有一个可供序列化的对象类Person类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace XMLSerializer
{
    [Serializable]
   public  class Person
    {
        private string name;

      [XmlElementAttribute(ElementName ="姓名")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string sex;
        [XmlElementAttribute(ElementName = "性别")]
        public string Sex
        {
            get { return sex; }
            set { sex = value; }
        }
        private int age;
        [XmlElementAttribute(ElementName = "年龄")]
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
        public Person()
        {

        }

        public Person(string _name,string _sex,int  _age)
        {
            Name = _name;
            Sex = _sex;
            Age = _age;
        }
    }
}

二、序列化的过程
1、建立一个流对象如Stream等。
2、建立一个序列化对象XmlSerialize。
3、调用XmlSerialize对象的Deserialize方法。

Person p1 = new Person("张三","男",20);
            try
            {
                FileStream fs = new FileStream("person.xml",FileMode.Create);
                //序列化
                XmlSerializer xs = new XmlSerializer(typeof(Person));
                xs.Serialize(fs,p1);
                fs.Close();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("序列化成功");

三、反序列化过程

//反序列化
            try
            {
                FileStream fileStream = new FileStream("person.xml",FileMode.Open,FileAccess.Read);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
                Person p = (Person)xmlSerializer.Deserialize(fileStream);
                Console.WriteLine(p.Name + p.Sex + p.Age);
            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
            }

参考资料:
Person 类的来源,C# 类用XmlSerializer进行序列化和反序列化进行文件读写的一个简单例子: http://www.52php.cn/article/p-zdxzlvri-gg.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读