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
Release: 2025-01-04 00:01:42
Original
562 people have browsed it

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

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;
}
Copy after login
  1. Create an XmlSerializer instance with the appropriate root and type attributes:
XmlSerializer serializer = new XmlSerializer(typeof(item[]), 
                                 new XmlRootAttribute() { ElementName = "items" });
Copy after login
  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() );
Copy after login

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

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

Deserialization using XElement

  1. Parse the XML into an XElement object:
XElement xElem2 = XElement.Parse(xml); //XElement.Load(...)
Copy after login
  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"));
Copy after login

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!

source:php.cn
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