In one of my objects I have a dictionary that is serialized by implementing IXmlSerializable
:
public SerializableStringDictionary Parameters { get; set; }
When I serialize a list of these object with the normal .NET serializer it serializes fine, however deserialization is only doing a single object - elements in the XML file that follow the serializable dictionary are getting skipped.
For example, I have a list of <MaintenanceIndicators>
. I show only one below, but this is a List<MaintenanceIndicator>
in the code. The serialization of a list with multiple entries works fine but deserializing multiple only gives me 1 MaintenanceIndicator
in the List. Its parameters property however is deserialized ok. No exceptions are thrown in the code.
I use the following code for deserialization:
public void ReadXml(XmlReader reader)
{
bool wasEmpty = reader.IsEmptyElement;
// jump to <parameters>
reader.Read();
if (wasEmpty)
return;
// read until we reach the last element
while (reader.NodeType != System.Xml.XmlNodeType.EndElement)
{
// jump to <item>
reader.MoveToContent();
// jump to key attribute and read
reader.MoveToAttribute("key");
string key = reader.GetAttribute("key");
// jump to value attribute and read
reader.MoveToAttribute("value");
string value = reader.GetAttribute("value");
// add item to the dictionary
this.Add(key, value);
// jump to next <item>
reader.ReadStartElement("item");
reader.MoveToContent(); // workaround to trigger node type
}
}
My structure in XML looks as follows:
<MaintenanceIndicators>
<MaintenanceIndicator Id="1" Name="Test" Description="Test" Type="LimitMonitor" ExecutionOrder="1">
<Parameters>
<item key="Input" value="a" />
<item key="Output" value="b" />
<item key="Direction" value="GreaterThan" />
<item key="LimitValue" value="1" />
<item key="Hysteresis" value="1" />
</Parameters>
</MaintenanceIndicator>
<!-- Any subsequent MaintenanceIndicator indicator element will not be read -->
</MaintenanceIndicators>