国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#實現對象XML序列化的方法

2020-01-24 02:18:13
字體:
來源:轉載
供稿:網友

本文實例講述了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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 贵阳市| 汽车| 织金县| 长葛市| 邻水| 汉寿县| 南川市| 克拉玛依市| 石楼县| 郑州市| 绍兴县| 西贡区| 平乐县| 绵阳市| 子长县| 湄潭县| 石景山区| 中方县| 大田县| 永年县| 新田县| 乐安县| 石城县| 宜黄县| 全椒县| 鄂托克前旗| 栾川县| 徐水县| 璧山县| 莫力| 宣威市| 阿图什市| 沐川县| 嘉禾县| 古交市| 靖边县| 宁蒗| 夹江县| 竹溪县| 温宿县| 永仁县|