话不多说,直接上代码
public class HashtableSerailizable : Hashtable, IXmlSerializable
{
#region IXmlSerializable Membres
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
// Start to use the reader.
reader.Read();
// Read the first element ie root of this object
reader.ReadStartElement("dictionary");
// Read all elements
while (reader.NodeType != XmlNodeType.EndElement)
{
// parsing the item
reader.ReadStartElement("item");
// PArsing the key and value
string key = reader.ReadElementString("key");
string value = reader.ReadElementString("value");
// en reading the item.
reader.ReadEndElement();
reader.MoveToContent();
// add the item
this.Add(key, value);
}
// Extremely important to read the node to its end.
// next call of the reader methods will crash if not called.
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
// Write the root elemnt
writer.WriteStartElement("dictionary");
// Fore each object in this
foreach (object key in this.Keys)
{
object value = this[key];
// Write item, key and value
writer.WriteStartElement("item");
writer.WriteElementString("key", key.ToString());
writer.WriteElementString("value", value.ToString());
// write </item>
writer.WriteEndElement();
}
// write </dictionnary>
writer.WriteEndElement();
}
#endregion
public void SaveXml(string filename)
{
System.IO.StreamWriter W = null;
try
{
W = new System.IO.StreamWriter(filename);
System.Xml.Serialization.XmlSerializer S = new System.Xml.Serialization.XmlSerializer(this.GetType());
S.Serialize(W, this);
W.Close();
}
catch//(Exception ex)
{
if (W != null)
W.Close();
//System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
public void ReadXml(string filename)
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(filename);
if (doc.ChildNodes.Count == 0) return;
XmlNodeList ItemList = doc.ChildNodes[1].ChildNodes[0].ChildNodes;
for (int i = 0; i < ItemList.Count; i++)
{
this.Add(ItemList[i].ChildNodes[0].InnerText, ItemList[i].ChildNodes[1].InnerText);
}
}
catch
{
}
}
public HashtableSerailizable()
{
}
public HashtableSerailizable(string filename)
{
ReadXml(filename);
}
}
浙公网安备 33010602011771号