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

请参阅