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

本文实例讲述了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#程序设计有所帮助。

(0)

相关推荐

  • C#实现复杂XML的序列化与反序列化

    本文以一个实例的形式讲述了C#实现复杂XML的序列化与反序列化的方法.分享给大家供大家参考.具体方法如下: 已知.xml(再此命名default.xml)文件,请将其反序列化到一个实例对象. Default.XML文件如下: <?xml version="1.0" encoding="utf-8" ?> <config> <rules> <rule name="namea"> <params&

  • c#对象反序列化与对象序列化示例详解

    1.对象序列化的介绍 (1).NET支持对象序列化的几种方式二进制序列化:对象序列化之后是二进制形式的,通过BinaryFormatter类来实现的,这个类位于System.Runtime.Serialization.Formatters.Binary命名空间下.SOAP序列化:对象序列化之后的结果符合SOAP协议,也就是可以通过SOAP 协议传输,通过System.Runtime.Serialization.Formatters.Soap命名空间下的SoapFormatter类来实现的.XML

  • C#实现json的序列化和反序列化实例代码

    在做asp.net和unity进行http通信的时候,当unity客户端发出表单请求的时候,我要将他要请求的数据以json的格式返回给客户端,让客户端来解析.服务器端这一块就涉及到json的序列化和反序列化的问题. 两种方法都有例子,第一种是用泛型集合来存储的对象,然后将集合序列化一下:第二种是直接序列化的一个对象 复制代码 代码如下: using System;using System.Collections.Generic;using System.Web.Script.Serializat

  • C#中Serializable序列化实例详解

    本文实例讲述了C#中Serializable序列化.分享给大家供大家参考.具体分析如下: 概述: 序列化就是是将对象转换为容易传输的格式的过程,一般情况下转化打流文件,放入内存或者IO文件 中.例如,可以序列化一个对象,然后使用 HTTP 通过 Internet 在客户端和服务器之间传输该对象,或者和其它应用程序共享使用.反之,反序列化根据流重新构造对象. 一.几种序列化技术  1)二进制序列化保持类型保真度,这对于在应用程序的不同调用之间保留对象的状态很有用.例如,通过将对象序列化到剪贴板,可

  • C#中JavaScriptSerializer帮助类用法实例

    本文实例讲述了C#中JavaScriptSerializer帮助类用法.分享给大家供大家参考.具体如下: 关键代码如下: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.Script.Serialization; namespace YanZhiwei.DotNet3._5.Utilities.Common {    

  • 深入理解C#序列化与反序列化的详解

    在我们深入探讨C#序列化和反序列化之前我们先要明白什么是序列化,它又称串行化,是.NET运行时环境用来支持用户定义类型的流化的机制.序列化就是把一个对象保存到一个文件或数据库字段中去,反序列化就是在适当的时候把这个文件再转化成原来的对象使用.其目的是以某种存储形成使自定义对象持久化,或者将这种对象从一个地方传输到另一个地方..NET框架提供了两种串行化的方式:1.是使用BinaryFormatter进行串行化:2.使用SoapFormatter进行串行化:3.使用XmlSerializer进行串

  • C#中datatable序列化与反序列化实例分析

    本文实例讲述了C#中datatable序列化与反序列化,分享给大家供大家参考.具体方法如下: 一.datatable序列化 public string getSendDetailQuery(DateTime timeS, DateTime timeE, string sccount) { try { SmsOperate so = new SmsOperate(); //得到dt DataTable dtt = so.getSendDetailQuery(timeS, timeE, sccoun

  • C# JavaScriptSerializer序列化时的时间处理详解

    最近被序列化困扰了一下下.原因看下面代码 class Program { static void Main(string[] args) { var user = new User { UserId = "sb", CreateDate = DateTime.Now }; var serialier = new JavaScriptSerializer(); var json = serialier.Serialize(user); Console.WriteLine(json); C

  • C#序列化与反序列化(Serialize,Deserialize)实例详解

    本文实例讲述了C#序列化与反序列化(Serialize,Deserialize)实现方法.分享给大家供大家参考.具体分析如下: 如果要保存运行程序过程的数据要么保存到数据库中,要么新建一个普通的文件,然后把数据保存进去.但是这两者有个缺点就是,不能把原有数据的结构也保存进去.比如一个类中的字段值保存进去后再读取出来必须再解析下才行.序列化技术让你省去了解析的过程.保存后再读取时直接得到一个class 序列化的方式有三种:BinaryFormatter,SoapFormatter,XmlSeria

  • c#数据的序列化和反序列化(推荐版)

    开始用的.net 自带的DataContractJsonSerializer进行序列化和反序列化,当代码写完以后,调试,我X(原谅我的脏话,因为确实让我生气),实体因为有[DataContractAttribute(IsReference=true )] 这样一个属性,提示不能序列化,当然手改一下啦,改完以后,提示基类EntityObject 的这个属性不可以 MY God!! 后来也是因为DataContractJsonSerializer 反序列化成集合的时候不好使,所以才下定决心废弃.采用

随机推荐