Load XML Data (Key/Value Pairs) into Data Structure

macleojw picture macleojw · Sep 25, 2009 · Viewed 15.9k times · Source

I have an XML Data Source which contains a list of key/value pairs. I'm looking for a simple way to load the same data into an array or some other data structure so that I can easily look up the data. I can bind it to a GridView with a couple of clicks but I'm failing to find a straightforward way to load it into something that isn't a UI Control.

My data source looks like:

<SiteMap>
  <Sections>  
    <Section Folder="TradeVolumes" TabIndex="1" />
    <Section Folder="TradeBreaks" TabIndex="2" />
  </Sections>
</SiteMap>

I'm wanting to load key value pairs (Folder, TabIndex)

What is the best way to load the data?

Answer

Thomas Levesque picture Thomas Levesque · Sep 25, 2009

Using Linq to XML :

var doc = XDocument.Parse(xmlAsString);
var dict = new Dictionary<string, int>();
foreach (var section in doc.Root.Element("Sections").Elements("Section"))
{
    dict.Add(section.Attribute("Folder").Value, int.Parse(section.Attribute("TabIndex").Value));
}

You get a dictionary, which is basically a collection of key/value pairs