Loading XML data (key / value pairs) into a data structure
I have an XML Data Source that contains a list of key / value pairs. I'm looking for an easy way to load the same data into an array or some other data structure so that I can search for the data easily. I can bind it to the GridView with a few clicks, but I canβt find an easy way to load it into something that is not a UI control.
My datasource looks like this:
<SiteMap>
<Sections>
<Section Folder="TradeVolumes" TabIndex="1" />
<Section Folder="TradeBreaks" TabIndex="2" />
</Sections>
</SiteMap>
I want to load key value pairs (Folder, TabIndex)
What's the best way to load data?
source to share
Using Linq for 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 end up with a dictionary, which is basically a collection of key / value pairs.
source to share
Load it into DataSet using function
.ReadXml(string path)
with your data, you will have a dataset with two tables:
Sections
| section_id |
|------------|
| 0 |
Section
| Folder | TableIndex | Section_Id |
|----------------------------------------|
| TradeVolumes | 1 | 0 |
| TradeBreaks | 2 | 0 |
source to share
You can do something like this. The code below is based on the xml you included in your questions.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
namespace SimpleTestConsole
{
class Program
{
static void Main(string[] args)
{
string xmlFile =
@"<SiteMap> <Sections><Section Folder=""TradeVolumes"" TabIndex=""1"" /> <Section Folder=""TradeBreaks"" TabIndex=""2"" /> </Sections></SiteMap>";
XmlDocument currentDocument = new XmlDocument();
try
{
currentDocument.LoadXml(xmlFile);
}
catch (Exception ex)
{
throw ex;
}
string path = "SiteMap/Sections";
XmlNodeList nodeList = currentDocument.SelectNodes(path);
IDictionary<string, string> keyValuePairList = new Dictionary<string, string>();
foreach (XmlNode node in nodeList)
{
foreach (XmlNode innerNode in node.ChildNodes)
{
if (innerNode.Attributes != null && innerNode.Attributes.Count == 2)
{
keyValuePairList.Add(new KeyValuePair<string, string>(innerNode.Attributes[0].Value, innerNode.Attributes[1].Value));
}
}
}
foreach (KeyValuePair<string, string> pair in keyValuePairList)
{
Console.WriteLine(string.Format("{0} : {1}", pair.Key, pair.Value));
}
Console.ReadLine();
}
}
}
source to share
Use the XmlSerializer and deserialize it to your own type. Then use it as a data source A pretty simple example can be found here - http://msdn.microsoft.com/en-us/library/ms950721.aspx
source to share