XmlSerializer를 사용하여 개체를 역직렬화하는 방법

개체를 역직렬화할 때는 전송 형식에 따라 스트림을 만들지 파일 개체를 만들지 여부가 결정됩니다. 전송 형식이 결정된 뒤에는 필요에 따라 Serialize 또는 Deserialize 메서드를 호출할 수 있습니다.

개체를 역직렬화하려면

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

참고 항목