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

作者:shichen2014 时间:2022-02-11 01:30:59 

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

标签:C#,序列化
0
投稿

猜你喜欢

  • 浅析C#静态类,静态构造函数,静态变量

    2022-04-10 03:33:14
  • Java日常练习题,每天进步一点点(7)

    2023-11-27 00:34:58
  • Java 8 Stream操作类型及peek示例解析

    2021-07-17 20:42:08
  • OpenCV Java实现人脸识别和裁剪功能

    2022-08-21 01:47:23
  • Spring整合Quartz开发代码实例

    2022-03-12 16:37:26
  • SpringAop实现原理及代理模式详解

    2023-04-23 21:28:41
  • java精度计算代码 java指定精确小数位

    2023-07-31 03:03:58
  • Intellij搭建springmvc常见问题解决方案

    2023-07-23 12:53:29
  • Java安全框架——Shiro的使用详解(附springboot整合Shiro的demo)

    2022-05-29 09:46:46
  • C#实现对数组进行随机排序类实例

    2023-06-22 19:04:26
  • SpringBoot整合第三方技术的详细步骤

    2023-11-29 08:22:48
  • c#用for语句输出一个三角形的方法

    2023-12-17 05:46:53
  • java8中的lambda表达式简介

    2022-09-12 04:14:10
  • Java应用开源框架实现简易web搜索引擎

    2023-08-22 20:20:54
  • java中sleep方法和wait方法的五个区别

    2023-08-27 18:37:23
  • 深入了解Java核心类库--Math类

    2023-08-19 01:06:21
  • 小白2分钟学会Visual Studio如何将引用包打包到NuGet上

    2022-01-14 10:25:53
  • Collections.shuffle()方法实例解析

    2021-09-17 18:51:38
  • 使用Spring Cloud Feign作为HTTP客户端调用远程HTTP服务的方法(推荐)

    2022-11-09 11:40:37
  • mybatis-plus 查询传入参数Map,返回List<Map>方式

    2022-01-05 13:39:24
  • asp之家 软件编程 m.aspxhome.com