C#实现对象XML序列化的方法

所属分类: 软件编程 / C#教程 阅读数: 45
收藏 0 赞 0 分享

本文实例讲述了C#实现对象XML序列化的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
using system;
using system.xml;
using system.xml.serialization;
using system.text;
using system.io;
public class util
{
    /// <summary>
    /// 对象序列化成 xml string
    /// </summary>
    public static string xmlserialize<t>(t obj)
    {
        string xmlstring = string.empty;
        xmlserializer xmlserializer = new xmlserializer(typeof(t));
        using (memorystream ms = new memorystream())
        {
            xmlserializer.serialize(ms, obj);
            xmlstring = encoding.utf8.getstring(ms.toarray());
        }
        return xmlstring;
    }
    /// <summary>
    /// xml string 反序列化成对象
    /// </summary>
    public static t xmldeserialize<t>(string xmlstring)
    {
        t t = default(t);
        xmlserializer xmlserializer = new xmlserializer(typeof(t));
        using (stream xmlstream = new memorystream(encoding.utf8.getbytes(xmlstring)))
        {
            using (xmlreader xmlreader = xmlreader.create(xmlstream))
            {
                object obj = xmlserializer.deserialize(xmlreader);
                t = (t)obj;
            }
        }
        return t;
    }
}

stringwriter,xmlserializer将对象、对象集合序列化为xml格式的字符串, 同时描述如何进行反序列化.

c# 序列化 xmlserializer,binaryformatter,soapformatter

复制代码 代码如下:
//radio.cs
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";
  }
}
//cars.cs
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();
      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 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
  }
}

希望本文所述对大家的C#程序设计有所帮助。

更多精彩内容其他人还在看

winform用datagridview制作课程表实例

这篇文章主要介绍了winform用datagridview制作课程表的方法,实例分析了WinForm实现课程表的结构、数据库及调用技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#中winform控制textbox输入只能为数字的方法

这篇文章主要介绍了C#中winform控制textbox输入只能为数字的方法,包括使用keyPress事件限制键盘输入以及TextChanged事件限制粘贴等情况,来实现控制输入为数字的功能,需要的朋友可以参考下
收藏 0 赞 0 分享

C#省份城市下拉框联动简单实现方法

这篇文章主要介绍了C#省份城市下拉框联动简单实现方法,涉及字典的定义与索引的用法,是非常实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#处理MySql多个返回集的方法

这篇文章主要介绍了C#处理MySql多个返回集的方法,实现了对处理MySql多个返回集进行封装,是非常实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#无限参数的写法

这篇文章主要介绍了C#无限参数的写法,通过循环遍历再结合paras.Add方法实现无限参数的功能,是比较实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#反射应用实例

这篇文章主要介绍了C#反射应用,实例分析了通过反射实现多系统数据库的配置方法,是比较实用的技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#窗体传值实例汇总

这篇文章主要介绍了C#窗体传值,实例形式汇总了静态变量传值、委托传值、对话框之间的传值等常见应用技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

C#把数组中的某个元素取出来放到第一个位置的实现方法

这篇文章主要介绍了C#把数组中的某个元素取出来放到第一个位置的实现方法,涉及C#针对数组的常见操作技巧,非常具有实用价值,需要的朋友可以参考下
收藏 0 赞 0 分享

C#中Equality和Identity浅析

这篇文章主要介绍了C#中Equality和Identity浅析,本文先是讲解了Equality和Identity的定义,同时讲解了判断两个对象等价性的4种方法,需要的朋友可以参考下
收藏 0 赞 0 分享

在Linux上运行C#的方法

这篇文章主要介绍了在Linux上运行C#的方法,实例分析了Linux平台下Mono软件包的应用技巧,以及在此基础之上的C#运行方法,具有一定的参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多