給定一個空字典
<items> <item>
要使用XML 中的資料填充字典並將其序列化回來,我們將使用自訂類別和XmlSerializer 類別。
public class item { [XmlAttribute] public int id; [XmlAttribute] public string value; }
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 class:
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"));
以上是如何使用 C# 用 XML 資料填入字典?的詳細內容。更多資訊請關注PHP中文網其他相關文章!