在我的一个对象中,我有一个字典,它通过实现进行序列化IXmlSerializable
:
public SerializableStringDictionary Parameters { get; set; }
当我使用普通的 .NET 序列化程序序列化这些对象的列表时,它可以很好地序列化,但是反序列化只执行一个对象——XML 文件中遵循可序列化字典的元素被跳过。
例如,我有一个<MaintenanceIndicators>
. 我在下面只显示一个,但这是List<MaintenanceIndicator>
代码中的一个。具有多个条目的列表的序列化工作正常,但反序列化多个只给我MaintenanceIndicator
列表中的 1。但是,它的参数属性可以反序列化。代码中不会抛出异常。
我使用以下代码进行反序列化:
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
}
}
我在 XML 中的结构如下所示:
<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>