c# XML序列化与反序列化

原先一直用BinaryFormatter来序列化挺好,可是最近发现在WinCE下是没有办法进行BinaryFormatter操作,很不爽,只能改成了BinaryWriter和BinaryReader来读写,突然想到能不能用XML来序列化?于是在网上查了些资料便写了些实践性代码,做些记录,避免以后忘记。

序列化对象

    public class People     

{       

  [XmlAttribute("NAME")]         

  public string Name         { set; get; }         

 [XmlAttribute("AGE")]        

  public int Age         { set; get; }     

}    

[XmlRoot("Root")]    

public class Student : People     

{         

[XmlElement("CLASS")]         

public string Class         { set; get; }         

[XmlElement("NUMBER")]         

public int Number         { set; get; }     

}

void Main(string[] args)

{

     Student stu = new Student()            

      {                

           Age = 10,                 

    Class = "Class One",                 

    Name = "Tom",                 

    Number = 1             

  };             

XmlSerializer ser = new XmlSerializer(typeof(Student));             

ser.Serialize(File.Create("C:\\x.xml"), stu);

}

反序列化对象

            XmlSerializer ser = new XmlSerializer(typeof(Student));             

    Student stu = ser.Deserialize(File.OpenRead("C:\\x.xml")) as Student;

对象数组序列化

    public class People     

{         

[XmlAttribute("NAME")]         

public string Name         { set; get; }         

[XmlAttribute("AGE")]         

public int Age         { set; get; }     }     

[XmlRoot("Root")]     

public class Student : People     

{         

[XmlElement("CLASS")]         

public string Class         { set; get; }         

[XmlElement("NUMBER")]         

public int Number         { set; get; }     }

void Main(string[] args)

{

            List<Student> stuList = new List<Student>();             

    stuList.Add(new Student() { Age = 10, Number = 1, Name = "Tom", Class = "Class One" });             

    stuList.Add(new Student() { Age = 11, Number = 2, Name = "Jay", Class = "Class Two" });             

    stuList.Add(new Student() { Age = 12, Number = 3, Name = "Pet", Class = "Class One" });            

     stuList.Add(new Student() { Age = 13, Number = 4, Name = "May", Class = "Class Three" });             

    stuList.Add(new Student() { Age = 14, Number = 5, Name = "Soy", Class = "Class Two" });             

    XmlSerializer ser = new XmlSerializer(typeof(List<Student>));             

           ser.Serialize(File.Create("C:\\x.xml"), stuList);

}

对象数组反序列

            XmlSerializer ser = new XmlSerializer(typeof(List<Student>));             

    List<Student> stuList = ser.Deserialize(File.OpenRead("C:\\x.xml")) as List<Student>;             

    foreach (Student s in stuList)             

      {                 

        MessageBox.Show(string.Format("{0} : {1} : {2} : {3}",                     

        s.Name, s.Age, s.Class, s.Number));             }

序列化Dirctionary

    public struct DirectionList  

   {        

[XmlAttribute("Name")]         

public string Name;         

[XmlElement("Value")]         

public int Value;     }

void Main(string[] args)

{

            Dictionary<string, int> list = new Dictionary<string, int>();             

    list.Add("1", 100);               

    list.Add("2", 200);            

     list.Add("3", 300);            

     list.Add("4", 400);             

    list.Add("5", 500);             

    list.Add("6", 600);             

    list.Add("7", 700);             

    list.Add("8", 800);             

    list.Add("9", 900);

            List<DirectionList> dirList = new List<DirectionList>();             

    foreach (var s in list)            

     {                 

      dirList.Add(new DirectionList() { Name = s.Key, Value = s.Value });             

    }             

    XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));             

    ser.Serialize(File.Create("C:\\x.xml"), dirList);

}

这里还要讲一点,在XmlSerializer中,不支持Dirctionary<>类型的对象,所以在序列化这种最常见类型的时候,只能按照它的格式先创建一个可以别序列化的类型,这里我定义了一个结构体,当然你也可以定义成其他的类。将Dictionary<>中的数据依次放进结构体以后就可以放入流中了。

[XmlAttribute("Name")]意思是将这个字段作为xml的属性,属性名跟在“”中

[XmlElement("Value")]意思是将这个字段做为xml的元素。

反序列化Dirctionary

       XmlSerializer ser = new XmlSerializer(typeof(List<DirectionList>));             

    List<DirectionList> dirList = ser.Deserialize(                 

    File.OpenRead("C:\\x.xml")) as List<DirectionList>;             

    foreach (var v in dirList)             

    {                 

      Console.WriteLine("{0} : {1}", v.Name, v.Value);             

    }

其实我并不喜欢这个名称,感觉有点生化危机的feel,但是也就是这样了,没有太炫的地方,Deserialize反序列化。真希望.Net能集成Dirctionary<>对象,那我们这些懒人就方便了。

在需要序列化的队伍中,数组是很常见的类型,其次就是图片了

序列化图片

    public struct ImageStruct    

   {         

  [XmlAttribute("Number")]         

  public int number;        

  [XmlElement("Image")]        

  public byte[] picture;     }

  void Main(string[] args)

  {

      ImageStruct s = new ImageStruct() { number = 1, picture = File.ReadAllBytes(@"11.jpg") };             

    XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));             

    FileStream fs = File.Create("c:\\x.xml");             

    ser.Serialize(fs, s);             

    fs.Close();

}

一样的,采用结构体来保存图片,这里我还加了个图片的名字,到时候查找起来也方便一些

图片反序列化

       XmlSerializer ser = new XmlSerializer(typeof(ImageStruct));             

    ImageStruct s = (ImageStruct)ser.Deserialize(File.OpenRead("c:\\x.xml"));             

    pictureBox1.Image = Image.FromStream(new MemoryStream(s.picture));

没有花头的方式,利用memorystream来做缓存,这样会比较快一点,实际上我并没有怎么感觉。

图片数组序列化

    public struct ImageStruct     

  {         

    [XmlAttribute("Number")]         

    public int number;         

    [XmlElement("Image")]         

    public byte[] picture;     }

    void Main(string[] args)

    {

       List<ImageStruct> imageList = new List<ImageStruct>();             

    imageList.Add(new ImageStruct()             

    {                 

    number = 1,                 

    picture = File.ReadAllBytes(@"11.jpg")             

  });             

    imageList.Add(new ImageStruct()            

     {                 

      number = 2,                 

      picture = File.ReadAllBytes(@"22.jpg")             

    });

            XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));             

    FileStream fs = File.Create("c:\\x.xml");             

    ser.Serialize(fs, imageList);             

    fs.Close();

}

图片数组反序列化

            XmlSerializer ser = new XmlSerializer(typeof(List<ImageStruct>));             

    List<ImageStruct> s = (List<ImageStruct>)ser.Deserialize(File.OpenRead("c:\\x.xml"));             

    var im = from i in s                      

    where i.number == 1                      select i.picture;

            //var im = s.Where(p => p.number == 1).Select(p => p.picture);             

    foreach (var image in im)             

    {                 

      pictureBox1.Image = Image.FromStream(new MemoryStream(image));             

    }

这里还对数组结构进行了Linq查询,这样就可以很方便的查询图片了。

c# XML序列化与反序列化的更多相关文章

  1. XML 序列化与反序列化

    XML序列化与反序列化 1.将一个类转化为XML文件 /// <summary> /// 对象序列化成XML文件 /// </summary> /// <param na ...

  2. XmlSerializer 对象的Xml序列化和反序列化

    http://www.cnblogs.com/yukaizhao/archive/2011/07/22/xml-serialization.html 这篇随笔对应的.Net命名空间是System.Xm ...

  3. C#的XML序列化及反序列化

    webservice在工作中用到的很多,基本都是以XML格式问通讯内容,其中最关键的就是XML串的序列化及反序列化. XML的运用中有两种信息传递,一种为XML的请求信息,另一种为返回信息,要运用XM ...

  4. .NET XML序列化与反序列化

    闲着没事,写了两个通用的XML序列化与反序列化的方法. 贴出来当作笔记吧! /// <summary> /// XML序列化 /// </summary> /// <ty ...

  5. XmlSerializer 对象的Xml序列化和反序列化,XMLROOT别名设置

    这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间.   为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中 ...

  6. Xml序列化、反序列化帮助类

    之前从网络上找了一个Xml处理帮助类,并整理了一下,这个帮助类针对Object类型进行序列化和反序列化,而不需要提前定义Xml的结构,把它放在这儿供以后使用 /// <summary> / ...

  7. Windows phone 之XML序列化与反序列化

    为什么要做序列化和反序列化? 一个回答: 我们都知道对象是不能在网络中直接传输的,不过还有补救的办法.XML(Extensible Markup Language)可扩展标记语言,本身就被设计用来存储 ...

  8. C#操作Xml:XmlSerializer 对象的Xml序列化和反序列化

    这篇随笔对应的.Net命名空间是System.Xml.Serialization:文中的示例代码需要引用这个命名空间. 为什么要做序列化和反序列化? .Net程序执行时,对象都驻留在内存中:内存中的对 ...

  9. C#实现接口xml序列化与反序列化

    C#实现接口xml序列化与反序列化   C#中接口无法被xml序列化,提示不支持.百度和bing也搜不到,只好自己动手写了 原理上肯定支持,.Net自己的xml序列化有一个IXmlSerializab ...

随机推荐

  1. Android 组件系列-----Activity保存状态

    本篇随笔将详细的讲解Activity保存状态的概念,也就是saving activity state. 一.Activity状态保持概念 保存Activity的状态是非常重要的,例如我们在玩一个游戏的 ...

  2. 深入分析Java Web技术(1)

    BS网络模型的基本过程: 当我们在浏览器中输入"www.google.com"的时候,首先会请求DNS服务器对域名进行解析成都应的IP地址,然后根据这个IP地址在互联网上找到谷歌的 ...

  3. Android使用的设计模式2——策略模式

    今天讲解一下策略模式,策略模式也是很常用的设计模式,对多种算法或者数据结构选择使用的情况下,经常会使用策略模式来管理这些算法.下面会简单讲解一下策略模式的概念和基本实现.然后结合Android里面的实 ...

  4. Scala 深入浅出实战经典 第65讲:Scala中隐式转换内幕揭秘、最佳实践及其在Spark中的应用源码解析

    王家林亲授<DT大数据梦工厂>大数据实战视频 Scala 深入浅出实战经典(1-87讲)完整视频.PPT.代码下载:百度云盘:http://pan.baidu.com/s/1c0noOt6 ...

  5. asp Gridview绑定形式获取行号

    Gridview中使用<%# Container.DataItemIndex %>取得当前行的序号 而在Repeater控件中使用Container.ItemIndex取得当前行的序号 & ...

  6. gem install 出现Errno::ECONNRESET: Connection reset by peer - SSL_connect (https://api.rubygems.org

    在安装了rvm来管理多版本的ruby之后,想在不同环境下安装一些gems,结果gem install puma 之后,发现一次又一次失败. gem install 出现Errno::ECONNRESE ...

  7. 使用 CountDownLatch 控制多个线程执行顺序

    已同步更新至:http://dxjia.cn/2015/08/countdownlatch-use/ 有时候会有这样的需求,多个线程同时工作,然后其中几个可以随意并发执行,但有一个线程需要等其他线程工 ...

  8. 打包时Xcode报:此证书的签发者无效Missing iOS Distribution signing identity

    问题描述 今天准备打包上传AppStore,结果Xcode报以下错误:Missing iOS Distribution signing identity for XXXXXX 查看证书后发现,Deve ...

  9. Crystal Reports 支持的纸张种类

    DefaultPaperSize Paper10x14 254 x 355.6 mm Paper11x17 279.4 x 431.8 mm PaperA3 A3 ?,297 x 420 mm Pap ...

  10. 《objective-c基础教程》学习笔记(十)—— 内存管理

    本篇博文,将给大家介绍下再Objective-C中如何使用内存管理.一个程序运行的时候,如果不及时的释放没有用的空间内存.那么,程序会越来越臃肿,内存占用量会不断升高.我们在使用的时候,就会感觉很卡, ...