程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成對象XML序列化的辦法

C#完成對象XML序列化的辦法

編輯:C#入門知識

C#完成對象XML序列化的辦法。本站提示廣大學習愛好者:(C#完成對象XML序列化的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是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#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved