串行化XML(三)

  串行化XML() 串行化XML() 可以將對象很方便、簡單的串行化爲XML格式,  除了可以將對象串行化爲XML格式以外,還可以將其串行化爲二進制、soap格式。<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

NET Framework通過Reflection提供自動Serialization的機制。當一個對象被序列化(Serialized)的時候,它的類名,Assembly,以及類實例的所有數據成員都將被寫入存儲介質中。Serialization引擎保持對所有已經被序列化的對象引用的追蹤,以確保相同的對象引用最多隻被序列化一次。
通常,一個Serialization過程會由formatter(例如BinaryFormatterSoapFormatter)的Serialize方法引發。

一個類能夠被序列化有兩種方式:

¨         將此class簡單地標記爲Serializable

¨         爲此class實現ISerializable接口,並將此class標記爲Serializable
聲明一個可被序列化的類

<Serializable()> _

Public Class Book

    Public bookname As String

    Public bookID As Integer

End Class

使用BinaryFormatter來將上面的序列化爲二進制格式文件Book.datBinaryFormatter位於

System.Runtime.Serialization.Formatters.Binary命名空間

 

Dim book As New book

        book.BookID = 1

        book.BookName = "數學"

        Dim formatter As BinaryFormatter = New BinaryFormatter

        Dim stream As stream = New FileStream("Book.dat", FileMode.Create, FileAccess.Write, FileShare.None)

        formatter.Serialize(stream, book)

        stream.Close()

經過BinaryFormatter序列化 serialize)的數據仍然能夠通過BinaryFormatter反序列化(deserialize)回來。

Dim formatter As BinaryFormatter = New BinaryFormatter

        Dim stream As stream = New FileStream("Book.dat", FileMode.Open, FileAccess.Read, FileShare.None)

        Dim book As Book = CType(formatter.Deserialize(stream), Book)

        stream.Close()

        MessageBox.Show("Book Name:" & book.bookname & vbCrLf & "Book ID:" & book.bookID)

       同串行化爲xml一樣,也可以忽略任意一個可以使用NonSerialized屬性進行選擇

              <NonSerialized()> _

    Public bookname As String

用類似的方法同樣也可以將對象序列化爲SOAP格式,我們使用SoapFormatter

Dim book As New book

        book.bookID = 1

        book.bookname = "English"

        Dim formatter As SoapFormatter = New SoapFormatter

        Dim stream As stream = New FileStream("Book.xml", FileMode.Create, FileAccess.Write, FileShare.None)

        formatter.Serialize(stream, Book)

        stream.Close()

所生成的Book.xml格式爲:

<SOAP-ENV:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:clr="http://schemas.microsoft.com/soap/encoding/clr/1.0" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<SOAP-ENV:Body>

<a1:Book id="ref-1" xmlns:a1="http://schemas.microsoft.com/clr/assem/e%2C%20Version%3D1.0.1.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">

<bookname id="ref-3">English</bookname>

<bookID>1</bookID>

</a1:Book>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>

總結:

Serialization.NET中一種實現對象持久性(Persistent)的機制。它是一個將對象中的數據轉換成一個單一元素(通常是Stream)的過程。它的逆過程是DeserializationSerialization的核心概念是將一個對象的所有數據看作一個獨立的單元。
一般說來,在兩種情況下非常需要Serialization

1)  當我們希望能夠將對象當前的狀態完整地保存到存儲介質中,以便我們以後能夠精確地還原對象時

2)  當我們希望將對象從一個應用程序空間(Application domain)傳遞到另一個應用程序空間時。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章