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

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

Barbara Streisand
Release: 2025-01-04 11:56:35
Original
433 people have browsed it

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

Serializing and Deserializing to a Dictionary from Custom XML Without XElement

When presented with an empty Dictionary and custom XML data, such as the example provided:

<items>
  <item>
Copy after login

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;
}
Copy after login

An example dictionary can be declared like so:

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

To deserialize the XML into the dictionary, create an XmlSerializer object:

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

The deserialization process can then be performed:

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

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() );
Copy after login

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(...);
Copy after login

Deserialization

XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
var newDict = xElem2.Descendants("item")
                    .ToDictionary(x => (int)x.Attribute("id"), x => (string)x.Attribute("value"));
Copy after login

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!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template