[C#基础]c#中的XmlSerializer类

原文链接:http://www.cnblogs.com/nhxy/archive/2010/11/16/1878409.html


何为序列化?何为反序列化?引用msdn上的一句话就是——XML 序列化是将对象的公共属性 (Property) 和字段转换为序列格式(这里是指 XML)以便存储或传输的过程。反序列化则是从 XML 输出中重新创建原始状态的对象。因此,可以将序列化视为将对象的状态保存到流或缓冲区的方法。


先总结一下:

1.序列化的时候,一般要传入流以及类作为参数,若该流为写入流,则会写进文件里。

2.反序列化的时候,一般要传入流作为参数,若该流为读取流,则会读取文件。


一、

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

namespace ConsoleApplication1
{
    class SimpleSerializer
    {
        /// <summary>
        /// 序列化对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="t">对象</param>
        /// <returns></returns>
        public static string Serialize<T>(T t)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());
                xz.Serialize(sw, t);
                return sw.ToString();
            }
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <param name="type">对象类型</param>
        /// <param name="s">对象序列化后的Xml字符串</param>
        /// <returns></returns>
        public static object Deserialize(Type type, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(type);
                return xz.Deserialize(sr);
            }
        }
    }
}

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

namespace ConsoleApplication1
{
    [Serializable]
    public class UserInfo
    {
        private int m_UserId;
        [XmlElement("userId")]
        public int UserId
        {
            get { return m_UserId; }
            set { m_UserId = value; }
        }

        private string m_UserName;
        [XmlElement("userName")]
        public string UserName
        {
            get { return m_UserName; }
            set { m_UserName = value; }
        }
    }
}

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            TestOne();
            Console.WriteLine();
            TestTwo();
            Console.WriteLine();
            TestThree();
            Console.WriteLine();
            TestFour();
            Console.ReadLine();
        }

        public static void TestOne()
        {
            UserInfo info = new UserInfo() { UserId = 1, UserName = "Guozhijian" };
            Console.WriteLine(SimpleSerializer.Serialize<UserInfo>(info));
        }

        public static void TestTwo()
        {
            List<UserInfo> list = new List<UserInfo>();
            list.Add(new UserInfo() { UserId = 1, UserName = "Guozhijian" });
            list.Add(new UserInfo() { UserId = 2, UserName = "Zhenglanzhen" });
            Console.WriteLine(SimpleSerializer.Serialize<List<UserInfo>>(list));
        }

        public static void TestThree()
        {
            string s = SimpleSerializer.Serialize<UserInfo>(new UserInfo() { UserId = 1, UserName = "Guozhijian" });
            UserInfo info = SimpleSerializer.Deserialize(typeof(UserInfo), s) as UserInfo;
            Console.WriteLine(info.UserId.ToString() + ", " + info.UserName);
        }

        public static void TestFour()
        {
            List<UserInfo> list = new List<UserInfo>();
            list.Add(new UserInfo() { UserId = 1, UserName = "Guozhijian" });
            list.Add(new UserInfo() { UserId = 2, UserName = "Zhenglanzhen" });

            string s = SimpleSerializer.Serialize<List<UserInfo>>(list);
            List<UserInfo> newList = SimpleSerializer.Deserialize(typeof(List<UserInfo>), s) as List<UserInfo>;
            foreach (var info in newList)
            {
                Console.WriteLine(info.UserId.ToString() + ", " + info.UserName);
            }
        }
    }
}

运行结果:



二、

using System;
using System.Collections.Generic;
using System.Text;

namespace SimpleSerialize
{
    [Serializable]
    public class Radio
    {
        public bool hasTweeters;
        public bool hasSubWoofers;
        public double[] stationPresets;

        [NonSerialized]
        public string radioID = "XF-552RR6";
    }
}

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

namespace SimpleSerialize
{
    [Serializable]
    public class Car
    {
        public Radio theRadio = new Radio();
        public bool isHatchBack;
    }

    [Serializable, XmlRoot(Namespace = "http://www.intertech.com")]
    public class JamesBondCar : Car
    {
        [XmlAttribute]
        public bool canFly;
        [XmlAttribute]
        public bool canSubmerge;

        public JamesBondCar(bool skyWorthy, bool seaWorthy)
        {
            canFly = skyWorthy;
            canSubmerge = seaWorthy;
        }
        // The XmlSerializer demands a default constructor!
        public JamesBondCar() { }
    }
}

//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

// For the formatters.
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace SimpleSerialize
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Fun with Object Serialization *****\n");

            // Make a JamesBondCar and set state.
            JamesBondCar jbc = new JamesBondCar();
            jbc.canFly = true;
            jbc.canSubmerge = false;
            jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 };
            jbc.theRadio.hasTweeters = true;

            // Now save / Load the car to a specific file.
            SaveAsBinaryFormat(jbc, "CarData.dat");
            LoadFromBinaryFile("CarData.dat");
            SaveAsSoapFormat(jbc, "CarData.soap");
            SaveAsXmlFormat(jbc, "CarData.xml");
            SaveListOfCars();
            SaveListOfCarsAsBinary();

            LoadAsXmlFormat(jbc, "CarData.xml");
            Console.ReadLine();
        }

        #region Save / Load as Binary Format
        static void SaveAsBinaryFormat(object objGraph, string fileName)
        {
            // Save object to a file named CarData.dat in binary.
            BinaryFormatter binFormat = new BinaryFormatter();

            using (Stream fStream = new FileStream(fileName,
                  FileMode.Create, FileAccess.Write, FileShare.None))
            {
                binFormat.Serialize(fStream, objGraph);
            }
            Console.WriteLine("=> Saved car in binary format!");
        }

        static void LoadFromBinaryFile(string fileName)
        {
            BinaryFormatter binFormat = new BinaryFormatter();

            // Read the JamesBondCar from the binary file.
            using (Stream fStream = File.OpenRead(fileName))
            {
                JamesBondCar carFromDisk =
                  (JamesBondCar)binFormat.Deserialize(fStream);
                Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly);
            }
        }
        #endregion

        #region Save as SOAP Format
        // Be sure to import System.Runtime.Serialization.Formatters.Soap 
        // and reference System.Runtime.Serialization.Formatters.Soap.dll.
        static void SaveAsSoapFormat(object objGraph, string fileName)
        {
            // Save object to a file named CarData.soap in SOAP format.
            SoapFormatter soapFormat = new SoapFormatter();

            using (Stream fStream = new FileStream(fileName,
              FileMode.Create, FileAccess.Write, FileShare.None))
            {
                soapFormat.Serialize(fStream, objGraph);
            }
            Console.WriteLine("=> Saved car in SOAP format!");
        }
        #endregion

        #region Save as XML Format
        static void SaveAsXmlFormat(object objGraph, string fileName)
        {
            // Save object to a file named CarData.xml in XML format.
            XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar),
              new Type[] { typeof(Radio), typeof(Car) });

            using (Stream fStream = new FileStream(fileName,
              FileMode.Create, FileAccess.Write, FileShare.None))
            {
                xmlFormat.Serialize(fStream, objGraph);
            }
            Console.WriteLine("=> Saved car in XML format!");
        }
        #endregion

        #region Load as XML Format
        static void LoadAsXmlFormat(object objGraph, string fileName)
        {
            XmlSerializer a = new XmlSerializer(objGraph.GetType());
            using (StreamReader fStream = new StreamReader(fileName))
            {
                JamesBondCar b = a.Deserialize(fStream) as JamesBondCar;
                Console.WriteLine("=> Loaded car in XML format!");
                Console.WriteLine("Can this car fly? : {0}", b.canFly);
            }
        }
        #endregion

        #region Save collection of cars
        static void SaveListOfCars()
        {
            // Now persist a List<> of JamesBondCars.
            List<JamesBondCar> myCars = new List<JamesBondCar>();
            myCars.Add(new JamesBondCar(true, true));
            myCars.Add(new JamesBondCar(true, false));
            myCars.Add(new JamesBondCar(false, true));
            myCars.Add(new JamesBondCar(false, false));

            using (Stream fStream = new FileStream("CarCollection.xml",
              FileMode.Create, FileAccess.Write, FileShare.None))
            {
                XmlSerializer xmlFormat = new XmlSerializer(typeof(List<JamesBondCar>),
                  new Type[] { typeof(JamesBondCar), typeof(Car), typeof(Radio) });
                xmlFormat.Serialize(fStream, myCars);
            }
            Console.WriteLine("=> Saved list of cars!");
        }

        static void SaveListOfCarsAsBinary()
        {
            // Save ArrayList object (myCars) as binary.
            List<JamesBondCar> myCars = new List<JamesBondCar>();

            BinaryFormatter binFormat = new BinaryFormatter();
            using (Stream fStream = new FileStream("AllMyCars.dat",
              FileMode.Create, FileAccess.Write, FileShare.None))
            {
                binFormat.Serialize(fStream, myCars);
            }
            Console.WriteLine("=> Saved list of cars in binary!");
        }
        #endregion
    }
}

运行结果:



  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值