In the project, you need a dictionary to save the key-value pair. The type is dictionary <string, list <string>. An error occurs when serialization to the file stream. the xmlserializer in net does not support dictionary. There are many solutions on the Internet, but they are complicated. They always feel that they are not steadfast (afraid of bugs). From another perspective, the data type is converted during serialization and deserialization to achieve serialization. Code As follows: /**/ /// <Summary>
///This class is used for XML serialization on generic type dictionary
/// </Summary>
Public Class Dictionaryholder
{
Public String Logicalname = "" ;
Public List < String > Physicalnames = New List < String > ();
}
/**/ /// <Summary>
///Loads the specified database.
/// </Summary>
/// <Param name = "Database">The database.</Param>
Public Void Load ( String Database)
{
Filestream FS = Null ;
Try
{
Xmlserializer XS = New Xmlserializer ( Typeof (List < Dictionaryholder > ));
FS = New Filestream (Database, filemode. Open, fileaccess. Read, fileshare. Read );
List < Dictionaryholder > Holders = (List < Dictionaryholder > ) XS. deserialize (FS );
This . _ Dictionary. Clear ();
Foreach (Dictionaryholder holder In Holders)
{
This. _ Dictionary. Add (holder. logicalname, Holder. physicalnames );
}
}
Catch (Exception ex)
{
Throw;
}
Finally
{
If(FS! = Null)
FS. Close ();
}
}
/**/ /// <Summary>
///Saves the specified database.
/// </Summary>
/// <Param name = "Database">The database.</Param>
Public Void Save ( String Database)
{
Filestream FS = Null ;
Try
{
List < Dictionaryholder > Holders = New List < Dictionaryholder > ();
Foreach ( String Key In This . _ Dictionary. Keys)
{
Dictionaryholder holder = New Dictionaryholder ();
Holder. logicalname = Key;
Holder. physicalnames = This . _ Dictionary [Key];
Holders. Add (holder );
}
Xmlserializer XS = New Xmlserializer ( Typeof (List < Dictionaryholder > ));
FS = New Filestream (Database, filemode. Create, fileaccess. Write, fileshare. Read );
Xs. serialize (FS, holders );
}
Catch (Exception ex)
{
Throw;
}
Finally
{
If(FS! = Null)
FS. Close ();
}
}
After testing, it can work normally. Here we actually use the target conversion method to convert the object to be serialized to a custom type that supports serialization, during deserialization, the object type is first deserialized into a custom object type, and then the final object is constructed.
I personally think Microsoft should add XML serialization support for dictionary, because its data structure can be easily mapped to the XML document: the key value is mapped to a node, the object corresponding to this key value is mapped to the subnode of this node.