I\'m looking for a key/value pair object that I can include in a web service.
I tried using .NET\'s System.Collections.Generic.KeyValuePair<> class, but it doe
I don't think there is as Dictionary<> itself isn't XML serializable, when I had need to send a dictionary object via a web service I ended up wrapping the Dictionary<> object myself and adding support for IXMLSerializable.
///
/// Represents an XML serializable collection of keys and values.
///
/// The type of the keys in the dictionary.
/// The type of the values in the dictionary.
[XmlRoot("dictionary")]
public class SerializableDictionary : Dictionary, IXmlSerializable
{
#region Constants
///
/// The default XML tag name for an item.
///
private const string DEFAULT_ITEM_TAG = "Item";
///
/// The default XML tag name for a key.
///
private const string DEFAULT_KEY_TAG = "Key";
///
/// The default XML tag name for a value.
///
private const string DEFAULT_VALUE_TAG = "Value";
#endregion
#region Protected Properties
///
/// Gets the XML tag name for an item.
///
protected virtual string ItemTagName
{
get
{
return DEFAULT_ITEM_TAG;
}
}
///
/// Gets the XML tag name for a key.
///
protected virtual string KeyTagName
{
get
{
return DEFAULT_KEY_TAG;
}
}
///
/// Gets the XML tag name for a value.
///
protected virtual string ValueTagName
{
get
{
return DEFAULT_VALUE_TAG;
}
}
#endregion
#region Public Methods
///
/// Gets the XML schema for the XML serialization.
///
/// An XML schema for the serialized object.
public XmlSchema GetSchema()
{
return null;
}
///
/// Deserializes the object from XML.
///
/// The XML representation of the object.
public void ReadXml(XmlReader reader)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
bool wasEmpty = reader.IsEmptyElement;
reader.Read();
if (wasEmpty)
{
return;
}
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.ReadStartElement(ItemTagName);
reader.ReadStartElement(KeyTagName);
TKey key = (TKey)keySerializer.Deserialize(reader);
reader.ReadEndElement();
reader.ReadStartElement(ValueTagName);
TValue value = (TValue)valueSerializer.Deserialize(reader);
reader.ReadEndElement();
this.Add(key, value);
reader.ReadEndElement();
reader.MoveToContent();
}
reader.ReadEndElement();
}
///
/// Serializes this instance to XML.
///
/// The writer to serialize to.
public void WriteXml(XmlWriter writer)
{
XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
foreach (TKey key in this.Keys)
{
writer.WriteStartElement(ItemTagName);
writer.WriteStartElement(KeyTagName);
keySerializer.Serialize(writer, key);
writer.WriteEndElement();
writer.WriteStartElement(ValueTagName);
TValue value = this[key];
valueSerializer.Serialize(writer, value);
writer.WriteEndElement();
writer.WriteEndElement();
}
}
#endregion
}