By default, xmlserializer Cannot serialize the dictionary, so that xmlserializer can be used.CompositionThe idictionary cannot be used in the cache, storage mode, or asmx service. You can use the ixmlserializable interface to customize a serializabledictionary <tkey, tvalue>.
/// <Summary>
/// Generic dictionary classes supporting XML serialization
/// </Summary>
/// <Typeparam name = "tkey"> </typeparam>
/// <Typeparam name = "tvalue"> </typeparam>
[Xmlroot ( " Dictionary " )]
Public Class Serializabledictionary < Tkey, tvalue > : Dictionary < Tkey, tvalue > , Ixmlserializable
{
Public Serializabledictionary ()
: Base ()
{
}
Public Serializabledictionary (idictionary < Tkey, tvalue > Dictionary)
: Base (Dictionary)
{
}
Public Serializabledictionary (iequalitycomparer < Tkey > Comparer)
: Base (Comparer)
{
}
Public Serializabledictionary ( Int Capacity)
: Base (Capacity)
{
}
Public Serializabledictionary ( Int Capacity, iequalitycomparer < Tkey > Comparer)
: Base (Capacity, comparer)
{
}
Protected Serializabledictionary (serializationinfo, streamingcontext context)
: Base (Info, context)
{
}
# RegionIxmlserializable members
PublicXMLSCHEMA getschema ()
{
Return Null;
}
/// <Summary>
/// Generate the object from the XML Representation of the object
/// </Summary>
/// <Param name = "Reader"> </param>
Public Void Readxml (system. xml. xmlreader reader)
{
Xmlserializer keyserializer = New Xmlserializer ( Typeof (Tkey ));
Xmlserializer valueserializer = New Xmlserializer ( Typeof (Tvalue ));
If (Reader. isemptyelement | ! Reader. Read ())
{
Return ;
}
While (Reader. nodetype ! = Xmlnodetype. endelement)
{
Reader. readstartelement ( " Item " ); // CJB
Reader. readstartelement ( " Key " );
Tkey key = (Tkey) keyserializer. deserialize (Reader );
Reader. readendelement ();
Reader. readstartelement ("Value");
Tvalue=(Tvalue) valueserializer. deserialize (Reader );
Reader. readendelement ();
Reader. readendelement ();
This. Add (Key, value );
Reader. movetocontent ();
}
Reader. readendelement ();
}
/// <Summary>
/// Convert an object to its XML Representation
/// </Summary>
/// <Param name = "Writer"> </param>
Public Void Writexml (system. xml. xmlwriter writer)
{
Xmlserializer keyserializer = New Xmlserializer ( Typeof (Tkey ));
Xmlserializer valueserializer = New Xmlserializer ( Typeof (Tvalue ));
Foreach (Tkey key In This . Keys)
{
Writer. writestartelement ( " Item " );
Writer. writestartelement ("Key");
Keyserializer. serialize (writer, key );
Writer. writeendelement ();
writer. writestartelement ( " value " );
tvalue = This [Key];
valueserializer. serialize (writer, value);
writer. writeendelement ();
Writer. writeendelement ();
}
}
# Endregion
}
Of course, any custom class or built-in type can customize their serializable formats by implementing ixmlserializable.