Home >Backend Development >C++ >How to Serialize and Deserialize a Dictionary to Custom XML Without Using XElement?

How to Serialize and Deserialize a Dictionary to Custom XML Without Using XElement?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 06:26:40793browse

How to Serialize and Deserialize a Dictionary to Custom XML Without Using XElement?

Serializing and Deserializing a Dictionary from Custom XML Without XElement

Consider a scenario where you have a Dictionary and you need to serialize it to and deserialize it from a custom XML format like the following:

<items>
  <item>

To achieve this serialization and deserialization without using XElement:

Serialization

  1. Create a temporary item class:
public class Item
{
    [XmlAttribute]
    public int Id;
    [XmlAttribute]
    public string Value;
}
  1. Initialize a Dictionary instance:
Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "one" }, { 2, "two" }
};
  1. Create an XmlSerializer instance:
XmlSerializer serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute() { ElementName = "items" });
  1. Serialize the Dictionary into XML:
serializer.Serialize(stream, dict.Select(kv => new Item() { Id = kv.Key, Value = kv.Value }).ToArray());

Deserialization

  1. Deserialize the XML into an array of Item objects:
var orgDict = ((Item[])serializer.Deserialize(stream))
               .ToDictionary(i => i.Id, i => i.Value);

Alternative Using XElement

If you later decide to use XElement, here's how you can serialize and deserialize:

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 to Custom XML Without Using XElement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn