Home >Backend Development >C++ >How to Serialize and Deserialize a Dictionary from Custom XML Without Using XElement?
Serializing and Deserializing to a Dictionary
When presented with an empty Dictionary
<items> <item>
the task of populating the dictionary with the provided keys and values and serializing it back into XML can be achieved without using XElement.
Deserialization
A temporary item class can be introduced:
public class item { [XmlAttribute] public int id; [XmlAttribute] public string value; }
An example dictionary can be declared like so:
Dictionary<int, string> dict = new Dictionary<int, string>() { {1,"one"}, {2,"two"} };
To deserialize the XML into the dictionary, create an XmlSerializer object:
XmlSerializer serializer = new XmlSerializer(typeof(item[]), new XmlRootAttribute() { ElementName = "items" });
The deserialization process can then be performed:
var orgDict = ((item[])serializer.Deserialize(stream)) .ToDictionary(i => i.id, i => i.value);
Serialization
To serialize the dictionary back into XML, follow these steps:
serializer.Serialize(stream, dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );
Alternative: Using XElement (If Preferred)
If XElement is preferred, the following approach can be used:
Serialization
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(...);
Deserialization
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 Serialize and Deserialize a Dictionary from Custom XML Without Using XElement?. For more information, please follow other related articles on the PHP Chinese website!