質問

私は、キー/値ペアのリストが含まれているXMLデータソースを持っています。私は簡単にデータを検索できるように配列または他のデータ構造に同じデータをロードするための簡単な方法を探しています。私は数回のクリックでのGridViewにバインドすることができますが、私はUIコントロールではない何かにそれをロードするための簡単な方法を見つけることができないんです。

私のデータソースは次のようになります:

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

私は、キーと値のペア(フォルダ、のTabIndex)をロードしたいんだ。

データをロードするための最良の方法は何ですか?

役に立ちましたか?

解決

XMLへのLINQを使用します:

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));
}

あなたは基本的にキー/値ペアのコレクションである辞書を取得

他のヒント

機能をDataSetにそれをロードします。

.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