Home >Backend Development >C++ >How to Serialize and Deserialize a Dictionary to Custom XML Without Using XElement?
Consider a scenario where you have a Dictionary
<items> <item>
To achieve this serialization and deserialization without using XElement:
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);
If you later decide to use XElement, here's how you can serialize and deserialize:
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 Serialize and Deserialize a Dictionary to Custom XML Without Using XElement?. For more information, please follow other related articles on the PHP Chinese website!