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);
  • 相关阅读:
    学习进度(第三周)
    2019春季学期进度报告(十)
    团队软件开发第一次冲刺(六)
    单词 统计续
    团队软件开发第一次冲刺(五)
    团队软件开发第一次冲刺(四)
    团队软件开发第一次冲刺(三)
    团队软件开发第一次冲刺(二)
    团队软件开发第一次冲刺(一)
    2019春季学期进度报告(九)
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2566403.html
Copyright © 2011-2022 走看看