上面的代码把三个对象变为一个对象,因此在串行化过程中产生一个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