Caricare dati XML (coppie chiave / valore) nella struttura dei dati
-
16-09-2019 - |
Domanda
Ho una sorgente dati XML che contiene un elenco di coppie chiave / valore. Sto cercando un modo semplice per caricare gli stessi dati in un array o di qualche altra struttura di dati in modo che possa facilmente cercare i dati. Posso associarlo a un GridView con un paio di clic, ma sto riuscendo a trovare un modo semplice per caricarlo in qualcosa che non è un controllo dell'interfaccia utente.
La mia fonte di dati appare come:
<SiteMap>
<Sections>
<Section Folder="TradeVolumes" TabIndex="1" />
<Section Folder="TradeBreaks" TabIndex="2" />
</Sections>
</SiteMap>
Sono voler caricare coppie chiave valore (cartella, TabIndex)
Qual è il modo migliore per caricare i dati?
Soluzione
Utilizzo di 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));
}
Si ottiene un dizionario, che è fondamentalmente una raccolta di coppie chiave / valore
Altri suggerimenti
Caricare in un DataSet con la funzione
.ReadXml(string path)
Con i dati che si avrà un set di dati con 2 tavoli:
Sections
| section_id |
|------------|
| 0 |
Section
| Folder | TableIndex | Section_Id |
|----------------------------------------|
| TradeVolumes | 1 | 0 |
| TradeBreaks | 2 | 0 |
Si può fare qualcosa di simile, Il codice che segue si basa sulla sulla xml che avete inserito nelle vostre domande.
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();
}
}
}
Usa XmlSerializer e deserializzare nella tua proprio tipo. Quindi utilizzare come origine dati Piuttosto semplice esempio può essere trovato qui - http://msdn.microsoft.com/ it-it / library / ms950721.aspx