Home >Backend Development >C++ >How to Populate a Dictionary with XML Data Using C#?

How to Populate a Dictionary with XML Data Using C#?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 00:01:42647browse

How to Populate a Dictionary with XML Data Using C#?

Populating Dictionary with XML Data

Given an empty Dictionary and custom XML in the format:

<items>
  <item>

To populate the dictionary with data from the XML and serialize it back, we'll utilize a custom class and the XmlSerializer class.

Serialization using Custom Class

  1. Define a custom class item to act as a temporary container for the XML data:
public class item
{
    [XmlAttribute]
    public int id;
    [XmlAttribute]
    public string value;
}
  1. Create an XmlSerializer instance with the appropriate root and type attributes:
XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });
  1. Serialize the dictionary by converting it to an array of item objects and serializing the array:
serializer.Serialize(stream, 
              dict.Select(kv=>new item(){id = kv.Key,value=kv.Value}).ToArray() );

Deserialization using Custom Class

  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 prefer to use the XElement class:

Serialization using XElement

  1. Create an XElement object representing the XML structure:
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 using XElement

  1. Parse the XML into an XElement object:
XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
  1. Extract data from the XML using LINQ and populate the dictionary:
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 Populate a Dictionary with XML Data Using C#?. 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