【问题标题】:Load XML Data (Key/Value Pairs) into Data Structure将 XML 数据(键/值对)加载到数据结构中
【发布时间】:2009-09-25 12:41:53
【问题描述】:
我有一个包含键/值对列表的 XML 数据源。我正在寻找一种将相同数据加载到数组或其他数据结构中的简单方法,以便我可以轻松查找数据。我可以通过单击几下将其绑定到 GridView,但我无法找到一种直接的方法将其加载到不是 UI 控件的东西中。
我的数据源如下:
<SiteMap>
<Sections>
<Section Folder="TradeVolumes" TabIndex="1" />
<Section Folder="TradeBreaks" TabIndex="2" />
</Sections>
</SiteMap>
我要加载键值对(文件夹、TabIndex)
加载数据的最佳方式是什么?
【问题讨论】:
标签:
c#
asp.net
xml
xmldatasource
【解决方案1】:
使用 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));
}
你得到一个字典,它基本上是键/值对的集合
【解决方案2】:
使用函数将其加载到数据集中
.ReadXml(string path)
使用您的数据,您将拥有一个包含 2 个表的数据集:
Sections
| section_id |
|------------|
| 0 |
Section
| Folder | TableIndex | Section_Id |
|----------------------------------------|
| TradeVolumes | 1 | 0 |
| TradeBreaks | 2 | 0 |
【解决方案3】:
您可以这样做,下面的代码基于您在问题中包含的 xml。
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();
}
}
}