擴展 NameValueCollection 支援序列化
NameValueCollection 集合類別是不支援序列化,若將 NameValueCollection 類別的物件執行 XML 序列化會釋出如下的錯誤訊息。
因為 NameValueCollection 類別具 ICollection 介面,若此類別要支援序列化需包含 Add(String.String) 方法,可是問題是在 NameValueCollection 類別無法實作此方法。若要讓 NameValueCollection 可支援序列化,可繼承 NameValueCollection 類別並實作 IXmlSerializable 介面來達到支援序列化的需求。
我們繼承 NameValueCollection 類別命名為 TBNameValueCollection,並實作 IXmlSerializable 介面自行處理物件的序列化及反序列。
''' <summary>
''' 索引鍵和字串值的集合(鍵值不區分大小寫)。
''' </summary>
Public Class TBNameValueCollection
Inherits NameValueCollection
Implements IXmlSerializable
#Region " IXmlSerializable 介面 "
Public Function GetSchema() As System.Xml.Schema.XmlSchema Implements IXmlSerializable.GetSchema
Throw New NotImplementedException()
End Function
''' <summary>
''' 由 XML 反列化為物件。
''' </summary>
''' <param name="reader">XML 讀取器。</param>
Public Sub ReadXml(ByVal Reader As XmlReader) Implements IXmlSerializable.ReadXml
Dim oKeySerializer As New XmlSerializer(GetType(String))
Dim oValueSerializer As XmlSerializer = New XmlSerializer(GetType(String))
Dim sName As String
Dim sValue As String
If Reader.IsEmptyElement Then Exit Sub
While Reader.Read()
If Reader.NodeType = XmlNodeType.Element Then
If Reader.LocalName = "Item" Then
sName = Reader.GetAttribute("Name")
sValue = Reader.GetAttribute("Value")
Me.Add(sName, sValue)
End If
End If
End While
End Sub
''' <summary>
''' 將物件序列化為 XML。
''' </summary>
''' <param name="writer">XML 寫入器。</param>
Public Sub WriteXml(ByVal writer As XmlWriter) Implements IXmlSerializable.WriteXml
Dim N1 As Integer
For N1 = 0 To Me.Count - 1
writer.WriteStartElement("Item")
writer.WriteAttributeString("Name", Me.Keys(N1))
writer.WriteAttributeString("Value", Me.Item(N1))
writer.WriteEndElement()
Next
End Sub
#End Region
Sub New()
MyBase.New(StringComparer.CurrentCultureIgnoreCase)
End Sub
End Class
針對 TBNameValueCollection 類別執行 XML 序列化的結果如下。