利用XMLSerializer将对象串行化到XML

ZDNet软件频道 时间:2009-02-04 作者:Builder.com |  我要评论()
本文关键词:软件
微软已经意识到串行化数据的重要性,因此在.NET框架中包含了命名空以提供串行化功能,为用户自己编写串行化方法提供了一个框架。

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


百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134