我有一个XML数据源包含键/值对的列表。我在寻找一个简单的方法相同的数据加载到一个数组或其他一些数据结构,这样我可以很容易地查找数据。我可以把它绑定到一对夫妇的点击一个GridView,但我没有找到一个简单的方法将其加载到的东西是不是UI控件。

我的数据源是这样的:

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

我想加载密钥值对(文件夹,的TabIndex)

什么是加载数据的最佳方法?

有帮助吗?

解决方案

使用LINQ到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));
}

您得到一本字典,这基本上是键/值对的集合

其他提示

与该功能将其载入到数据集

.ReadXml(string path)

与您的数据,你将有一个数据集2个表:

Sections 

| section_id |
|------------|
| 0          |

Section

| Folder       | TableIndex | Section_Id | 
|----------------------------------------|
| TradeVolumes | 1          | 0          |
| TradeBreaks  | 2          | 0          |

您可以做这样的事情,下面的代码是基于上已包含在你的问题的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();


        }
    }
}

使用的XmlSerializer和反序列化到自己的类型。然后用它作为数据源 很简单的例子可以在这里找到 - http://msdn.microsoft.com/ EN-US /库/ ms950721.aspx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top