Given an empty Dictionary
<items> <item>
To populate the dictionary with data from the XML and serialize it back, we'll utilize a custom class and the XmlSerializer class.
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);
If you prefer to use the 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"));
The above is the detailed content of How to Populate a Dictionary with XML Data Using C#?. For more information, please follow other related articles on the PHP Chinese website!