2012-12-19 3 views
18

ho xml come segue:Come convertire XML dizionario

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <data name="LogIn">Log In</data> 
    <data name="Password">Password</data> 
</root> 

ho successo di farlo senza Linq, nessuno mi può aiutare a convertire il codice seguente per Linq:

using (XmlReader reader = XmlReader.Create(_xml)) 
{ 
    while (reader.Read()) 
    { 
     if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "data") 
     { 
      reader.MoveToAttribute("name"); 
      string key = reader.Value; 
      reader.MoveToContent(); 
      string value = reader.ReadElementContentAsString(); 
      _dictionary.Add(key, value); 
     } 
    } 
    reader.Close(); 
} 
+6

Plain le password di testo in un file XML ... –

risposta

20
var xdoc = XDocument.Load(path_to_xml); 
_dictionary = xdoc.Descendants("data") 
        .ToDictionary(d => (string)d.Attribute("name"), 
           d => (string)d); 
+1

solo per chiara XDocument xdoc = XDocument.Load (nome del file); – Vlad

+0

Ho ricevuto il seguente errore: 'System.Collections.Generic.IEnumerable ' non contiene una definizione per 'ToDictionary' e nessun metodo di estensione 'ToDictionary' che accetta un primo argomento di tipo 'System .Collections.Generic.IEnumerable 'potrebbe essere trovato (ti manca una direttiva using o un riferimento assembly?) –

+6

@RamzyAbourafeh Aggiungi 'using System.Linq;' così puoi usare i metodi di estensione LINQ . – ken2k

0
XDocument xdoc = XDocument.Load("test.XML"); 
var query = xdoc.Descendants("root") 
       .Elements() 
       .ToDictionary(r => r.Attribute("name").Value, 
          r => r.Value); 

Ricordate di includere:

using System.Linq; 
using System.Xml.Linq; 
0

Questa è una vecchia domanda, ma nel caso in cui qualcuno si imbatta in un 'Typed' xml (ad esempio da un file SharedPreference di un'app Android), è possibile gestirlo come di seguito: Ecco un esempio di tale xml che ho preso da un Instagram app.

<?xml version='1.0' encoding='utf-8' standalone='yes' ?> 
<map> 
<boolean name="pinnable_stickers" value="false" /> 
<string name="phone_number">+254711339900</string> 
<int name="score" value="0" /> 
<string name="subscription_list">[]</string> 
<long name="last_address_book_updated_timestamp" value="1499326818875" /> 
//...other properties 
</map> 

Nota l'incoerenza nella proprietà valore. Alcuni campi (ad esempio, tipo string) non sono definiti in modo esplicito.

var elements = XElement.Load(filePath) 
.Elements() 
.ToList(); 
var dict = new Dictionary<string, string>();  
var _dict = elements.ToDictionary(key => key.Attribute("name").Value, 
         val => val.Attribute("value") != null ? 
         val.Attribute("value").Value : val.Value);