串行化过程生成标准的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));