无法使用IXmlSerializable.ReadXml反序列化自定义词典

时间:2020-07-23 07:09:39

标签: c# serialization

我有一个自定义的Dictionary,它的键和值都具有字符串类型。

我需要能够读写这种格式的XML:

<MyDict>
   <Key1>Value1</Key1>
   <Key2>Value1</Key2>
   <Key3>Value1</Key3>
</MyDict>

我已经能够以所需的形式生成XML:

public class SerializableListItem : System.Collections.Generic.SortedDictionary<string, string>, IXmlSerializable
{
    public void WriteXml(XmlWriter writer)
    {
        foreach (var key in this.Keys)
        {
            writer.WriteElementString(XmlConvert.EncodeLocalName(key), this[key]);
        }
    }

但是,我正在努力实现ReadXml方法。现在,在this answer(以及其他)的帮助下,我写道:

public void ReadXml(XmlReader reader)
{
    this.Clear();
    reader.MoveToContent();
    while (reader.NodeType != XmlNodeType.EndElement)
    {
        while (reader.NodeType != XmlNodeType.Element)
        {
            if (reader.NodeType == XmlNodeType.EndElement)
            {
                reader.ReadEndElement();
                return;
            }

            reader.Read();
        }

        this.Add(XmlConvert.DecodeName(reader.LocalName), reader.ReadElementContentAsString());
        if (XmlNodeType.EndElement == reader.NodeType)
        {
            reader.ReadEndElement();
        }
    }
}

但这失败,并显示以下错误:

Run-time exception (line 31): There is an error in XML document (1, 63).

Stack Trace:

[System.Xml.XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements. Line 1, position 63.]
   at System.Xml.XmlReader.SetupReadElementContentAsXxx(String methodName)
   at System.Xml.XmlReader.ReadElementContentAsString()
   at SerializableListItem.ReadXml(XmlReader reader) :line 68
   at System.Xml.Serialization.XmlSerializationReader.ReadSerializable(IXmlSerializable serializable, Boolean wrappedAny)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderSerializableListItem.Read1_SerializableListItem()

[System.InvalidOperationException: There is an error in XML document (1, 63).]
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
   at Program.Main() :line 31

以下是完整的可复制代码:https://dotnetfiddle.net/vsnbIR

我错过了什么?

1 个答案:

答案 0 :(得分:0)

我终于找到了另一个答案。

这是我使用的 public void ReadXml(XmlReader reader) { if (reader.IsEmptyElement) { reader.Read(); return; } reader.Read(); while (reader.NodeType != XmlNodeType.EndElement) { switch (reader.NodeType) { case XmlNodeType.Element: var key = reader.Name; var value = reader.ReadElementContentAsString(); Add(key, value); break; default: // Comment, for instance. reader.Read(); break; } } // Consume the EndElement reader.Read(); } 实现:

bh

它正在工作,但我不十分清楚为什么。