这是我的班级结构:
class DataItem
{
public string Id { get; set; }
public string Type { get; set; }
private Dictionary<string, DataProperty> properties = new Dictionary<string, DataProperty>();
public Dictionary<string, DataProperty> Properties
{
get { return properties; }
set { properties = value; }
}
}
public class DataProperty
{
public string Key { get; set; }
public string Value { get; set; }
public bool Required { get; set; }
}
这是我想使用的 XML (注意:如果需要,我可以更改 xml):
<Data>
<DataItem>
<id>ph15</id>
<type>core</type>
<properties>
<DataProperty>
<key>size</key>
<value>50%</value>
<required>false</required>
</DataProperty>
<DataProperty>
<key>color</key>
<value>red</value>
<required>true</required>
</DataProperty>
</properties>
</DataItem>
<DataItem>
<id>ph234</id>
<type>core</type>
<properties>
</properties>
</DataItem>
</Data>
最终 XML 应该被加载到另一个字典中:
private Dictionary<string, DataItem> Mydata;
不幸的是,通用字典不可进行 xml 序列化。
解决方法是专门创建一个单独的字段来支持序列化,将字典的元素公开为键/值对列表。然后,您还必须用以下标记来标记字典成员XmlIgnore
属性。
或者,您可以使用 XmlSerializer 以外的其他东西(例如数据契约序列化器)它确实支持字典类型。
这是一个链接到一篇文章它提供了一个很好的示例,说明如何修改类型以支持使用字典的 XML 序列化。
如果您使用此代码,有一点很重要 - 序列化的项目可能以任意顺序出现在输出中。这是使用字典(无序)作为数据存储模型的结果。
[XmlIgnore()]
public Dictionary<string, DataProperty> Properties
{
set { properties = value; }
get { return properties ; }
}
[XmlArray("Stuff")]
[XmlArrayItem("StuffLine", Type=typeof(DictionaryEntry))]
public DictionaryEntry[] PropertiesList
{
get
{
//Make an array of DictionaryEntries to return
DictionaryEntry[] ret=new DictionaryEntry[Properties.Count];
int i=0;
DictionaryEntry de;
//Iterate through Stuff to load items into the array.
foreach (KeyValuePair<string, DataProperty> props in Properties)
{
de = new DictionaryEntry();
de.Key = props.Key;
de.Value = props.Value;
ret[i]=de;
i++;
}
return ret;
}
set
{
Properties.Clear();
for (int i=0; i<value.Length; i++)
{
Properties.Add((string)value[i].Key, (DataProperty)value[i].Value);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)