zoukankan      html  css  js  c++  java
  • How to: Begin Sample with Serialization and Deserialization an Object

    To serialize an object,

    first create the object that is to be serialized

    second set its public properties and fields.

    third you must determine the transport format in which the XML stream is to be stored, either as a stream or as a file.

    For example, if the XML stream must be saved in a permanent form, create a FileStream object.

    the steps detail in code:

    1. Create the object and set its public fields and properties.
    2. Construct a XmlSerializer using the type of the object. For more information, see the XmlSerializer class constructors.

    3. Call the Serialize method to generate either an XML stream or a file representation of the object's public properties and fields. The following example creates a file.

       
    public class MySerializableClass()
    {
      public string name{get;set;}
      public string id(get;set;)//public properties
      private string _sex;
      public int age;           //public fields
    }
    serialization code:
    MySerializableClass myObject = new MySerializableClass(); // Insert code to set properties and fields of the object. XmlSerializer mySerializer = new XmlSerializer(typeof(MySerializableClass)); // To write to a file, create a StreamWriter object. StreamWriter myWriter = new StreamWriter("myFileName.xml"); mySerializer.Serialize(myWriter, myObject); myWriter.Close();
    <?xml version="1.0" encoding="utf-8"?>
    <MySerializableClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <age>12</age>
      <name>wq</name>
      <id>1</id>
    </MySerializableClass>
    deserialization code:
    MySerializableClass myObject1;
                // Construct an instance of the XmlSerializer with the type
                // of object that is being deserialized.
                XmlSerializer mySerializer1 =
                new XmlSerializer(typeof(MySerializableClass));
                // To read the file, create a FileStream.
                FileStream myFileStream1 =
                new FileStream("myFileName.xml", FileMode.Open);
                // Call the Deserialize method and cast to the object type.
                myObject1 = (MySerializableClass)mySerializer1.Deserialize(myFileStream1);
  • 相关阅读:
    库头文件的导入导出宏
    VC 注册表读写
    改变QTableWidget 行高
    QMenu,QT的菜单添加
    error LNK2023: bad DLL or entry point 'msobj80.dll' 解决方法
    QT,QAction中的ToolTip
    QT 修改QTableWidget表头
    VS2008中 没有QT的代码智能提示
    VC 创建托盘,托盘tooltip。右键托盘菜单,点击别的地方会隐藏掉的问题。
    GDI+ 双缓冲
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2566403.html
Copyright © 2011-2022 走看看