C# 类用XmlSerializer进行序列化和反序列化进行文件读写的一个简单例子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyzxk888/article/details/6341009

和BinaryFormatter序列化一样,做一个可以序列化的类Person:

namespace Serializable
{
    [Serializable] //不可少!
    public class Person
    {
        private String name;
        private String sex;
        private int age;

        public Person() //XmlSerializer序列化要求一定要有无参数构造函数
        {
            name = "";
            sex = "";
            age = 0;
        }

        public Person(String n, String s, int a)
        {
            name = n;
            sex = s;
            age = a;
        }

        public String Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public String Sex
        {
            get
            {
                return sex;
            }
            set
            {
                sex = value;
            }
        }

        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
            }
        }
    }
}

 

//主运行程序

namespace Serializable
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("张三", "男", 20);
            //序列化
            try
            {
                FileStream fs = new FileStream("serialiable.xml", FileMode.Create);
                XmlSerializer xs = new XmlSerializer(typeof(Person));
                xs.Serialize(fs, p1);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("序列化成功!");

            Console.Read();

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

            Console.Read();
            Console.Read();
        }
    }
}

 

结果图:

 

生成的XML文件:

 

阅读更多

没有更多推荐了,返回首页