views:

30

answers:

1

Using a reference from... http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx I have a serializable generic dictionary.

One thing I wanted to do is to add the Key into the Attribute nodes of the Values (just because It's how I wanted it formatted). Oftentimes, the Key is just a string. Is there any way to force the class to adhere to this? It is telling me that TKey cannot be cast to string from read.GetAttribute("Key"); on the Value node.

    while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
    {
        reader.ReadStartElement("Entry");

        reader.ReadStartElement("Key");

        //TKey key = (TKey)keySerializaer.Deserialize(reader);

        reader.ReadEndElement();

        reader.ReadStartElement("Value");
            TKey key = reader.GetAttribute("Name");

        TValue value = (TValue)valueSerializer.Deserialize(reader);

        reader.ReadEndElement();

        this.Add(key, value); reader.ReadEndElement(); reader.MoveToContent();
    }

Likewise, the corrosponding 'WriteXml'...

        writer.WriteStartElement("Entry");

        writer.WriteStartElement("Key");
        keySerializaer.Serialize(writer, key);
        writer.WriteEndElement();

        writer.WriteStartElement("Value");
            writer.WriteAttributeString("Name", key.ToString());
        TValue value = this[key]; 
        valueSerializer.Serialize(writer, value);
        writer.WriteEndElement();

        writer.WriteEndElement();
+1  A: 

It may oftentimes be a string. What about the times when it is not?

How would you handle that and serialize the arbitrary content to an attribute?

The original code used keySerializer.Serialize(writer, key); for a reason.

If you know explicitly that the key is a string, you can change the code to something like public class StringKeyDictionary<TValue> : Dictionary<string, TValue>, IXmlSerializable and use your code.

andras