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);
  • 相关阅读:
    Spring Data JPA 入门篇
    44444444444444444444444444444444dddddddddd66666666666666666666666666
    1111111111111
    第二个随笔啊
    我的第一个Node web程序
    centos 6 不能上网
    开通博客园
    【转载】【超详细教程】使用Windows Live Writer 2012和Office Word 2013 发布文章到博客园全面总结
    Ajax返回值之XML、json类型
    XHR详细讨论
  • 原文地址:https://www.cnblogs.com/malaikuangren/p/2566403.html
Copyright © 2011-2022 走看看