HOW TO:序列化物件
若要序列化物件,首先建立要序列化的物件,並設定其公用屬性與欄位。若要執行這項作業,您必須判斷 XML 資料流儲存 (無論是資料流或檔案) 的傳輸格式。例如,若 XML 資料流必須以永久形式儲存,請建立 FileStream 物件。
注意: |
---|
如需更多 XML 序列化的範例,請參閱 XML 序列化的範例。 |
序列化物件
建立物件並設定其公用欄位與屬性。
使用物件的型別,建構 XmlSerializer。如需詳細資訊,請參閱 XmlSerializer 類別建構函式。
呼叫 Serialize 方法,產生 XML 資料流或物件之公用屬性與欄位的檔案表示方式。下列範例將建立檔案。
Dim myObject As MySerializableClass = New MySerializableClass() ' Insert code to set properties and fields of the object. Dim mySerializer As XmlSerializer = New XmlSerializer(GetType(MySerializableClass)) ' To write to a file, create a StreamWriter object. Dim myWriter As StreamWriter = New StreamWriter("myFileName.xml") mySerializer.Serialize(myWriter, myObject) myWriter.Close()
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();
另請參閱
工作
概念
建置日期:2010-03-10