如何使用 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);
    

另請參閱