现在的位置: 首页 > 综合 > 正文

How to: Begin Sample with Serialization and Deserialization an Object

2012年10月27日 ⁄ 综合 ⁄ 共 1743字 ⁄ 字号 评论关闭

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);

抱歉!评论已关闭.