Pregunta

Tengo una fuente de datos XML que contiene una lista de pares clave / valor. Estoy buscando una manera sencilla de cargar los mismos datos en una matriz o alguna otra estructura de datos para que pueda buscar fácilmente los datos. Puedo obligar a éste a un GridView con un par de clics, pero estoy de no poder encontrar una manera directa para cargarlo en algo que no es un control de interfaz de usuario.

Mi fuente de datos se ve así:

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

Estoy queriendo cargar pares de valores clave (carpeta, TabIndex)

¿Cuál es la mejor manera de cargar los datos?

¿Fue útil?

Solución

El uso de 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));
}

Se obtiene un diccionario, que es básicamente una colección de pares clave / valor

Otros consejos

Cargar en un conjunto de datos con la función

.ReadXml(string path)

Con los datos que tendrá un conjunto de datos con 2 tablas:

Sections 

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

Section

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

Se puede hacer algo como esto, el código a continuación se basa en el XML en el que ha incluido en sus preguntas.

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


        }
    }
}

Uso XmlSerializer y deserializar en su propio tipo. Luego usarlo como fuente de datos Muy sencillo ejemplo se puede encontrar aquí - http://msdn.microsoft.com/ en-us / library / ms950721.aspx

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top