myWallJSON myWallJSON - 1 year ago 83
C# Question

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

Having empty

Dictionary<int, string>
how to fill it with keys and values from XML like

<item id='int_goes_here' value='string_goes_here'/>

and serialize it back into XML not using XElement?

Answer Source

With the help of a temporary item class

public class item
    public int id;
    public string value;

Sample Dictionary:

Dictionary<int, string> dict = new Dictionary<int, string>()
    {1,"one"}, {2,"two"}


XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });


              dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );


var orgDict = ((item[])serializer.Deserialize(stream))
               .ToDictionary(i =>, i => i.value);


Here is how it can be done using XElement, if you change your mind.


XElement xElem = new XElement(
                    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"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download