梁某人

发展才是硬道理

导航

转:使用XMLSerializer类持久化数据

软在 .NET Framework 中通过System.Runtime.Serialization和System.Xml.Serialization提供了序列化功能,从这里我们可以看到微软已经承认了持久化数据的需要。System.Runtime.Serialization提供了开发自定义序列化解决方案的框架。System.XML.Serialization命名空间提供了以 XML 持久化对象的基本功能。下面让我们近距离看一下如何使用这一方法。

XML 的普通要求

XML 序列化是将一个对象的公有属性(property)和域(field)转换到一个序列化格式(在这里是 XML)用于存储或传输的过程。反序列化是从 XML 输出中按照对象的原始状态重新创建对象的过程。因此,你可以将序列化看作是一种将对象状态保存到一个流或缓冲区的方法。

序列的两个常用的地方是数据持久化和数据交换。持久化指在用户的会话间保存数据的过程。当应用程序关闭时数据被存储(序列化),当用户回来时数据被重新装载(反序列化)。数据交换是将数据提供其它系统的过程。使用序列化和 XML 可以很简单地实现数据交换。

对象中的数据在编程语句结构中被描述为类(class)、域(field)、属性(property)、基元类型(primitive type)、数组(array),甚至是以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 的格式。这可以通过一个 XML schema 文件提供。.NET Framework 含有一个 schema 生成工具 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 元素,或者告诉系统简单地忽略一个元素。下面重写了 VB.NET book 类,作为一个例子提供给大家:

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 代码片断将前面例子的输出进行了反序列化处理。

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.FileStream fs = new System.IO.FileStream("booktest.xml",
FileMode.Open);
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fs);
Book BookObject = (Book)(ser.Deserialize(reader));



posted on 2005-10-12 11:56  涛仔28  阅读(654)  评论(0编辑  收藏  举报