Pergunta

Eu tenho uma fonte de dados XML que contém uma lista de pares de chave / valor. Eu estou procurando uma maneira simples de carregar os mesmos dados em uma outra estrutura de dados de matriz ou para que eu possa facilmente procurar os dados. I pode vinculá-lo a um GridView com um par de cliques, mas eu estou deixando de encontrar uma maneira fácil de carregá-lo em algo que não é um controle de interface do usuário.

A minha fonte de dados se parece com:

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

Eu estou querendo carregar pares de valores-chave (pasta, TabIndex)

O que é a melhor maneira de carregar os dados?

Foi útil?

Solução

Usando o LINQ para 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));
}

Você recebe um dicionário, que é basicamente uma coleção de pares de chave / valor

Outras dicas

Coloque-o em um DataSet com a função

.ReadXml(string path)

com os seus dados, você terá um conjunto de dados com 2 tabelas:

Sections 

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

Section

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

Você pode fazer algo como isto, O código abaixo é baseada no no xml de ter incluído em suas perguntas.

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


        }
    }
}

Use XmlSerializer e desserializar-lo em seu próprio tipo. Em seguida, usá-lo como fonte de dados Muito exemplo simples pode ser encontrado aqui - http://msdn.microsoft.com/ en-us / library / ms950721.aspx

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top