DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> XML學習教程 >> XML詳解 >> 利用XMLSerializer將對象串行化到XML
利用XMLSerializer將對象串行化到XML
編輯:XML詳解     
微軟已經意識到串行化數據的重要性,因此在.Net框架中包含了命名空間System.Runtime.Serialization和System.Xml.Serialization以提供串行化功能,為用戶自己編寫串行化方法提供了一個框架。System.Xml.Serialization命名空間提供了將一個對象串行化為XML格式的基本方法。下面我們來看看如何使用這種方法。

XML的魅力
 
    串行化XML是指為了方便存儲或傳輸,把一個對象的公共的域和屬性保存為一種串行格式(這裡是XML格式)的過程。非串行化則是使用串行的狀態信息將對象從串行XML狀態還原成原始狀態的過程。因此,可以把串行化看作是將對象的狀態保存到流或緩沖區中的一種方法。

串行化的目的是數據存儲和數據轉換。數據存儲指的是在用戶會話時保存數據。當應用程序關閉時,數據被保存(串行化),而當用戶回來時,數據又被重新加載(非串行化)。數據轉換指將數據變換成能被另一個系統識別的格式。使用串行化和XML,可以很方便的進行數據轉換。

    對象中的數據可以是類、方法、屬性、私有類型、數組,在System.Xml.XmlElement或System.Xml.XmlAttribute對象中,它甚至可以是內嵌的XML。

    System.Xml.Serialization命名空間中的關鍵類是XmlSerializer。當然在該命名空間中還包括有關XML其他方面以及SOAP相關的其他類,不過我們的重點是XMLSerializer類。

XMLSerializer
    XmlSerializer類提供了把對象串行化為XML文件及把XML文檔非串行化為對象的方法。它還能讓用戶指定對象如何轉化為XML。可以把將被串行化的對象的類型作為類構造函數的參數。下面的C# 代碼說明了構造函數的用法。

    XmlSerializer ser = new XMLSerializer(typeof(objectToSerialize));

    下面是等價的VB.Net代碼:

    Dim ser As New XMLSerializer(GetType(objectToSerialize))

    實際的串行化過程在XmlSerializer類的Serialize方法中實現。該方法允許在串行化過程中調用TextWriter、Stream和XMLWriter對象。下面的例子代碼說明了如何調用該方法。在本例中一個對象被串行化保存到本地磁盤的一個文件當中。例子中首先是類聲明,後面緊接著是串行化源代碼。

using System;
namespace BuilderSerialization {
public class Address {
public Address() {}
public string Address1;
public string Address2;
public string City;
public string State;
public string Zip;
public string Country;
} }
using System;
namespace BuilderSerialization {
public class Author {
public Author() { }
public string FirstName;
public string MiddleName;
public string LastName;
public string Title;
public string Gender;
public Address AddressObject;
} }
namespace BuilderSerialization {
public class Book {
public Book() { }
public string Title;
public Author AuthorObject;
public string ISBN;
public double RetailPrice;
public string Publisher;
}}
using System;
using System.XML.Serialization;
using System.IO;
namespace BuilderSerialization {
class TestClass {
static void Main(string[] args) {
Book BookObject = new Book();
XmlSerializer ser = new XMLSerializer(typeof(Book));
TextWriter writer = new StreamWriter("booktest.XML");
BookObject.Title = "Practical LotusScript";
BookObject.ISBN = "1884777767 ";
BookObject.Publisher = "Manning Publications";
BookObject.RetailPrice = 43.95;
BookObject.AuthorObject = new Author();
BookObject.AuthorObject.FirstName = "Tony";
BookObject.AuthorObject.LastName = "Patton";
BookObject.AuthorObject.Gender = "Male";
BookObject.AuthorObject.AddressObject = new Address();
BookObject.AuthorObject.AddressObject.Address1 = "1 Main Street";
BookObject.AuthorObject.AddressObject.City = "Anywhere";
BookObject.AuthorObject.AddressObject.State = "KY";
BookObject.AuthorObject.AddressObject.Zip = "40000";
BookObject.AuthorObject.AddressObject.Country = "USA";
ser.Serialize(writer, BookObject);
writer.Close();
} } }

上面的代碼把三個對象變為一個對象,因此在串行化過程中產生一個XML文件。以下是例子程序產生的XML文檔:

<?XML version="1.0" encoding="utf-8"?>
<Book xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Title>Practical LotusScript</Title>
<AuthorObject>
<FirstName>Tony</FirstName>
<LastName>Patton</LastName>
<Gender>Male</Gender>
<AddressObject>
<Address1>1 Main Street</Address1>
<City>Anywhere</City>
<State>KY</State>
<Zip>40000</Zip>
<Country>USA</Country>
</AddressObject>
</AuthorObject>
<ISBN>1884777767 </ISBN>
<RetailPrice>43.95</RetailPrice>
<Publisher>Manning Publications</Publisher>
</Book>

注意串行化過程也能處理對象數據的嵌套。數據被轉換成可識別的格式,方便了數據重載(非串行化)以及向另一個系統的數據傳輸。在數據傳輸過程時,接收方系統需要知道XML文件的格式(如果預先不知道的話)。因此需要提供一個XML schema文件。.Net框架中的XSD.exe工具可以為串行化XML生成一個schema文件。

下面是用VB.Net編寫的例子代碼:

Public Class Address
Public Address1 As String
Public Address2 As String
Public City As String
Public State As String
Public Zip As String
Public Country As String
End Class
Public Class Author
Public FirstName As String
Public MiddleName As String
Public LastName As String
Public Title As String
Public Gender As String
Public AddressObject As Address
End Class
Public Class Book
Public AuthorObject As Author
Public Title As String
Public ISBN As String
Public RetailPrice As Double
Public Publisher As String
End Class
Imports System.XML.Serialization
Imports System.IO
Module Module1
Sub Main()
Dim BookObject As New Book
Dim ser As New XMLSerializer(GetType(Book))
Dim writer As New StreamWriter("booktest.XML")
With BookObject
.Title = "Practical LotusScript"
.ISBN = "1884777767 "
.Publisher = "Manning Publications"
.RetailPrice = 43.95
.AuthorObject = New Author
.AuthorObject.FirstName = "Tony"
.AuthorObject.LastName = "Patton"
.AuthorObject.Gender = "Male"
.AuthorObject.AddressObject = New Address
.AuthorObject.AddressObject.Address1 = "1 Main Street"
.AuthorObject.AddressObject.City = "Anywhere"
.AuthorObject.AddressObject.State = "KY"
.AuthorObject.AddressObject.Zip = "40000"
.AuthorObject.AddressObject.Country = "USA"
End With
ser.Serialize(writer, BookObject)
writer.Close()
End Sub
End Module

控制輸出
 
 
串行化過程生成標准的XML文件,數據成員轉換為XML元素。不過,並非所有的數據成員都變成元素,可以通過在類代碼中添加一些標記來控制輸出的XML文件。這樣,數據成員可以變換為XML屬性而非元素,也可以簡單的被忽略掉。下面的例子是一段經過修改後的book類VB.Net代碼。

Public Class Book
Public AuthorObject As Author
Public Title As String
<System.Xml.Serialization.XMLAttribute()> _
Public ISBN As String
<System.Xml.Serialization.XMLIgnoreAttribute()> _
Public RetailPrice As Double
Public Publisher As String
End Class

這段代碼告訴系統在生成XML文件時把類成員ISBN作為XML屬性,同時忽略掉RetailPrice成員。這種變化可以在生成的XML文件中可以看出:

<?XML version="1.0" encoding="utf-8"?>
<Book xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ISBN="1884777767 ">
<AuthorObject>
<FirstName>Tony</FirstName>
<LastName>Patton</LastName>
<Gender>Male</Gender>
<AddressObject>
<Address1>1 Main Street</Address1>
<City>Anywhere</City>
<State>KY</State>
<Zip>40000</Zip>
<Country>USA</Country>
</AddressObject>
</AuthorObject>
<Title>Practical LotusScript</Title>
<Publisher>Manning Publications</Publisher>
</Book>

以下是相應的C# 代碼:

public class Book {
public Book() { }
public string Title;
public Author AuthorObject;
[System.Xml.Serialization.XMLAttribute()]
public string ISBN;
[System.Xml.Serialization.XMLIgnoreAttribute()]
public double RetailPrice;
public string Publisher;
}

上面僅是稍微提了兩種標記符號。請查閱.Net文檔以獲得完整的標記符號。

非串行化
非串行化數據通過調用XMLSerializer類的Deserialize方法可以方便地實現。以下的VB.Net程序片斷完成上文中XML文檔的非串行化:

Dim BookObject As New Book
Dim ser As New XMLSerializer(GetType(Book))
Dim fs As New System.IO.FileStream("booktest.XML", FileMode.Open)
Dim reader As New System.XML.XMLTextReader(fs)
BookObject = CType(ser.Deserialize(reader), Book)

該程序把結果數據放入內存備用。下面是等價的C# 代碼:

XmlSerializer ser = new XMLSerializer(typeof(Book));
System.IO.FileStreamfs = new System.IO.FileStream("booktest.XML",
FileMode.Open);
System.Xml.XmlTextReader reader = new System.Xml.XMLTextReader(fs);
Book BookObject = (Book)(ser.Deserialize(reader));


---------------------------------------------------
作者簡介:Tony Patton是一名專業應用程序開發人員,知識面廣泛,獲得了Java、 VB、 Lotus和XML認證。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved