我有一个XML数据源,其中包含键/值对的列表。我正在寻找一种简单的方法将相同的数据加载到数组或其他数据结构中,以便我可以轻松查找数据。我可以通过几次点击将它绑定到GridView,但我没有找到一种直接的方法将其加载到不是UI控件的东西。
我的数据来源如下:
<SiteMap>
<Sections>
<Section Folder="TradeVolumes" TabIndex="1" />
<Section Folder="TradeBreaks" TabIndex="2" />
</Sections>
</SiteMap>
我想加载键值对(Folder,TabIndex)
加载数据的最佳方法是什么?
答案 0 :(得分:8)
使用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));
}
你得到一个字典,它基本上是键/值对的集合
答案 1 :(得分:1)
使用函数
将其加载到DataSet中.ReadXml(string path)
使用您的数据,您将拥有一个包含2个表格的数据集:
Sections
| section_id |
|------------|
| 0 |
Section
| Folder | TableIndex | Section_Id |
|----------------------------------------|
| TradeVolumes | 1 | 0 |
| TradeBreaks | 2 | 0 |
答案 2 :(得分:1)
您可以执行以下操作,以下代码基于您在问题中包含的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();
}
}
}
答案 3 :(得分:0)
使用XmlSerializer并将其反序列化为您自己的类型。然后将其用作数据源 可以在这里找到相当简单的例子 - http://msdn.microsoft.com/en-us/library/ms950721.aspx