惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Help Net Security
博客园 - Franky
GbyAI
GbyAI
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
aimingoo的专栏
aimingoo的专栏
博客园_首页
MongoDB | Blog
MongoDB | Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recent Announcements
Recent Announcements
Scott Helme
Scott Helme
有赞技术团队
有赞技术团队
M
MIT News - Artificial intelligence
C
CERT Recently Published Vulnerability Notes
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Jina AI
Jina AI
F
Fortinet All Blogs
N
Netflix TechBlog - Medium
L
LangChain Blog
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hacker News: Front Page
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
AI
AI
T
Troy Hunt's Blog
Microsoft Azure Blog
Microsoft Azure Blog
阮一峰的网络日志
阮一峰的网络日志
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
S
Secure Thoughts
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗
人人都是产品经理
人人都是产品经理
Blog — PlanetScale
Blog — PlanetScale
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
S
Security @ Cisco Blogs
Cloudbric
Cloudbric
E
Exploit-DB.com RSS Feed
Attack and Defense Labs
Attack and Defense Labs

博客园 - 胖子

Markdown Reader 插件改造 Visual Studio Code 使用心得 Philips K700 使用感受 清除UTF-8文件的BOM头 powershell 相关 FireFox在windows2003的操作系统支持Windows Media Player插件 关于javascript编码url的中文参数 [转]IIS 6.0中配置HTTP Gzip压缩 数码相机在windows2003下的问题 MyGeneration连接MySql数据库的解决办法 一个简单的操作活动目录的类(ADHelper) SmartPhone下解决rm、rmvb等格式电影播放的方案(参考意见) 读写类似web.config的xml格式文件 - 胖子 - 博客园 Awstats 安装使用说明 关于博客园的聚合问题 关于保持页面滚动条位置的一些体会 胖子的故事(四) 胖子的故事(三) - 胖子 胖子的故事(二) - 胖子
XML、二进制、SOAP的序列化
胖子 · 2010-02-24 · via 博客园 - 胖子

2010-02-24 13:45  胖子  阅读(840)  评论()    收藏  举报

目的

将对象序列化之后,可以以文件的形式保存下来。

区别

  XML 二进制 SOAP
序列化类 XmlSerializer BinaryFormatter SoapFormatter
SerializableAttribute 标记 不需要 需要 需要
ISerializable 接口 不需要 需要 需要
无参构造函数 必须有 不需要 不需要
被序列化的数据成员属性 public all all
序列化后的大小

实现

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main( string[] args )
        {
            SerializeByXml();
            SerializeByBinary();
            SerializeBySoap();
        }

        static void SerializeByXml()
        {
            string filePath = @"b:\XmlSerializer.dat";

            if( !File.Exists( filePath ) )
            {
                List<Product> list1 = new List<Product>();
                for( int i = 1; i <= 10; i++ )
                    list1.Add( new Product { ProductID = i, ProductName = "产品名称_xml_" + i } );

                XmlSerializer xsSerialize = new XmlSerializer(typeof (List<Product>));
                using( Stream fsWrite = new FileStream( filePath, FileMode.Create, FileAccess.Write, FileShare.None ) )
                {
                    xsSerialize.Serialize( fsWrite, list1 );
                    fsWrite.Close();
                }
            }

            List<Product> list2;
            XmlSerializer xsDeserialize = new XmlSerializer( typeof( List<Product> ) );
            using( Stream fsRead = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.None ) )
            {
                list2 = (List<Product>)xsDeserialize.Deserialize( fsRead );
                fsRead.Close();
            }
            foreach( Product p in list2 )
            {
                Console.WriteLine( p );
            }
        }

        static void SerializeByBinary()
        {
            string filePath = @"b:\BinarySerializer.dat";

            if( !File.Exists( filePath ) )
            {
                List<Product> list1 = new List<Product>();
                for( int i = 1; i <= 10; i++ )
                    list1.Add( new Product { ProductID = i, ProductName = "产品名称_binary_" + i } );

                BinaryFormatter xsSerialize = new BinaryFormatter();
                using( Stream fsWrite = new FileStream( filePath, FileMode.Create, FileAccess.Write, FileShare.None ) )
                {
                    xsSerialize.Serialize( fsWrite, list1 );
                    fsWrite.Close();
                }
            }

            List<Product> list2;
            BinaryFormatter xsDeserialize = new BinaryFormatter();
            using( Stream fsRead = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.None ) )
            {
                list2 = (List<Product>)xsDeserialize.Deserialize( fsRead );
                fsRead.Close();
            }
            foreach( Product p in list2 )
            {
                Console.WriteLine( p );
            }
        }

        static void SerializeBySoap()
        {
            string filePath = @"b:\SoapSerializer.dat";

            if( !File.Exists( filePath ) )
            {
                List<Product> list1 = new List<Product>();
                for( int i = 1; i <= 10; i++ )
                    list1.Add( new Product { ProductID = i, ProductName = "产品名称_soap_" + i } );

                SoapFormatter xsSerialize = new SoapFormatter();
                using( Stream fsWrite = new FileStream( filePath, FileMode.Create, FileAccess.Write, FileShare.None ) )
                {
                    xsSerialize.Serialize( fsWrite, list1.ToArray() );
                    fsWrite.Close();
                }
            }

            List<Product> list2;
            SoapFormatter xsDeserialize = new SoapFormatter();
            using( Stream fsRead = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.None ) )
            {
                list2 = new List<Product>( (Product[])xsDeserialize.Deserialize( fsRead ) );
                fsRead.Close();
            }
            foreach( Product p in list2 )
            {
                Console.WriteLine( p );
            }
        }
    }

    [Serializable]
    public class Product
    {
        public int ProductID { get; set; }
        public string ProductName { get; set; }

        public override string ToString()
        {
            return string.Format("ProductID:{0}\t\tProductName:{1}", ProductID, ProductName);
        }
    }
}
注意点
SOAP不能直接序列化List<T>这种类型的集合,但可以序列化数组[],所以序列化List<T>.ToArray()对象;
反序列化时,先强制转换为数组,然后再用数组构造List<T>