序列化和反序列化

序列化是将类型转化为二进制类型,可以保存到文件,或者用于传输

反序列化是将二进制类型转化为文本等类型

这个是对象的序列化

   #region 对象的序列化与反序列化(字节)

        /// <summary>

        /// 这个是序列化

        /// </summary>

        /// <param name="data"></param>

        /// <returns></returns>

        public static byte[] Serialize(object data)

        {

            BinaryFormatter formatter = new BinaryFormatter();

            MemoryStream streamMemory = new MemoryStream();

            formatter.Serialize(streamMemory, data);

            byte[] binaryData = streamMemory.GetBuffer();

            streamMemory.Close();

            return binaryData;

        }



        /// <summary>

        /// 这个是反序列化

        /// </summary>

        /// <param name="binaryData"></param>

        /// <returns></returns>

        public static object Deserialize(byte[] binaryData)

        {

            BinaryFormatter formatter = new BinaryFormatter();

            MemoryStream streamMemory = new MemoryStream(binaryData);

            object data = formatter.Deserialize(streamMemory);

            streamMemory.Close();

            return data;

        }

        #endregion

  基本的序列化和反序列化

View Code
 #region 从Xml文件通过XPath选择XmlNode

        /// <summary>

        /// 从Xml文件通过XPath选择XmlNode

        /// 编写时间:2011.11.09

        /// 是否完成:是

        /// </summary>

        /// <param name="sFile">XML文件地址</param>

        /// <param name="sXPath">XPath语句</param>

        /// <returns>单个XmlNode</returns>

        public static XmlNode SelectXmlNode(string sFile, string sXPath)

        {

            XmlDocument doc = new XmlDocument();

            doc.Load(sFile);

            return doc.SelectSingleNode(sXPath);

        }

        #endregion
View Code
#region Xml字符串反序列化到对象

        /// <summary>

        /// Xml字符串反序列化到对象

        /// 编写时间:2011.11.09

        /// 是否完成:是

        /// </summary>

        /// <param name="type">类型</param>

        /// <param name="sXml">Xml</param>

        /// <returns>object对象</returns>

        public static object DeserializeXml(Type type, string sXml)

        {

            using (StringReader sr = new StringReader(sXml))

            {

                XmlSerializer xs = new XmlSerializer(type);

                return xs.Deserialize(sr);

            }

        }

        #endregion

 

你可能感兴趣的:(反序列化)