如何使用 XmlSerializer 將物件還原序列化

當您還原序列化物件時,傳輸格式決定您會建立資料流或檔案物件。 決定傳輸格式後,您可視需要呼叫 SerializeDeserialize 方法。

還原序列化物件

  1. 使用要還原序列化的物件型別,建構 XmlSerializer

  2. 呼叫 Deserialize 方法以產生物件的複本。 在還原序列化時,您必須將所傳回物件轉換成原始的類型 (如下面的範例所示),其會從檔案將物件還原序列化 (雖然其也能從串流還原序列化)。

    ' Construct an instance of the XmlSerializer with the type
    ' of object that is being deserialized.
    Dim mySerializer As New XmlSerializer(GetType(MySerializableClass))
    ' To read the file, create a FileStream.
    Using myFileStream As New FileStream("myFileName.xml", FileMode.Open)
        ' Call the Deserialize method and cast to the object type.
        Dim myObject = CType( _
             mySerializer.Deserialize(myFileStream), MySerializableClass)
     End Using
    
    // Construct an instance of the XmlSerializer with the type
    // of object that is being deserialized.
    var mySerializer = new XmlSerializer(typeof(MySerializableClass));
    // To read the file, create a FileStream.
    using var myFileStream = new FileStream("myFileName.xml", FileMode.Open);
    // Call the Deserialize method and cast to the object type.
    var myObject = (MySerializableClass)mySerializer.Deserialize(myFileStream);
    

另請參閱