空着Dictionary<int, string>如何用XML中的键和值填充它
Dictionary<int, string>
<items> <item id='int_goes_here' value='string_goes_here'/> </items>
并使用XElement将其序列化回XML?
在一个临时item班的帮助下
item
public class item { [XmlAttribute] public int id; [XmlAttribute] public string value; }
样本字典:
Dictionary<int, string> dict = new Dictionary<int, string>() { {1,"one"}, {2,"two"} };
。
XmlSerializer serializer = new XmlSerializer(typeof(item[]), new XmlRootAttribute() { ElementName = "items" });
序列化
serializer.Serialize(stream, dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );
反序列化
var orgDict = ((item[])serializer.Deserialize(stream)) .ToDictionary(i => i.id, i => i.value);
如果您改变主意,可以 使用XElement 完成此 操作 。
XElement xElem = new XElement( "items", dict.Select(x => new XElement("item",new XAttribute("id", x.Key),new XAttribute("value", x.Value))) ); var xml = xElem.ToString(); //xElem.Save(...);
XElement xElem2 = XElement.Parse(xml); //XElement.Load(...) var newDict = xElem2.Descendants("item") .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));