IXmlSerializable Dictionary problem

荒凉一梦 提交于 2019-12-01 18:55:16

Why would it contain a root? You aren't adding one in Serialize, where you create the XmlWriter... I wonder if you should have something more like (C#, sorry):

public string Serialize() {
    StringBuilder sb = new StringBuilder();
    XmlSerializer ser = new XmlSerializer(
        typeof(SerializableDictionary<TKey, TValue>));
    using (XmlWriter writer = XmlWriter.Create(sb)) {
        ser.Serialize(writer, this);
    }
    return sb.ToString();
}

This uses the regular XmlSerializer core for things like writing the outer element(s). Alternatively, change Serialize to include an outer element of your choosing.

Not an answer, but I found 2 bugs in Shimmy's code (thanks by the way) and one gotcha for those trying to use this against .Net 2.0

The bugs are related to each other. The calls to:

WriteData(IsKeyAttributable, writer, True, entry.Key)
WriteData(IsValueAttributable, writer, False, entry.Value)

should be

WriteData(IsKeyAttributable, writer, True, DirectCast(entry.Key, TKey))
WriteData(IsValueAttributable  AndAlso IsKeyAttributable, writer, False, CType(entry.Value, TValue))

i.e If the Key is not able to be an XML attribute, then the value cannot be an XML attribute. Also, need to cast the entry.Key and entry.Value to it's TKey/TValue, otherwise the XMLSerializer complains later on. Also

Similarly the call

Dim value = ReadData(Of TValue)(IsValueAttributable, reader, False)

should be

Dim value = ReadData(Of TValue)(IsValueAttributable AndAlso IsKeyAttributable, reader, False)

i.e Agin check that the key is attributale if the value is attributable

And for those targetting .Net runtime 2.0 you will need the GetIsAttributable predicate declared as

Private Shared ReadOnly GetIsAttributable As Predicate(Of Type) = Function(t) DirectCast(AttributableTypes, IList).Contains(t)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!