2011-03-18 4 views
1

Comme dans le code, j'ai besoin d'analyser un xml et d'obtenir un type de ContactData. Mon but est d'analyser une simple liste de contacts comme indiqué dans le code, mais sans spécifier les données de structure, comme le code commenté.Xml, Linq to Class

Si je tente d'utiliser le code commenté que je reçois une exception qui ne passerait-il si j'utilise seul le code ci-dessous:

  XDocument xmlDocument = XDocument.Parse(data); 
      var result = from entry in xmlDocument.Descendants("contact") 
      select new ContactData 
      { 
       //Data = (Dictionary<string,object>)(from element in entry.Elements() select new Dictionary<string, object>().ToDictionary(o => o.Key, o => o.Value)), 

       Data = new Dictionary<string, object> 
       { 
        {"uid", entry.Element("uid").Value}, 
        {"name", entry.Element("name").Value}, 
        {"email", entry.Element("email").Value}, 
        {"message", entry.Element("message").Value}, 
        {"state", entry.Element("state").Value} 
       },     
       State = (States)Enum.Parse(typeof(States), entry.Element("state").Value) 
      }; 
      return result.ToArray<ContactData>(); 

Comment corriger cela?

Data = (Dictionary<string,object>)(from element in entry.Elements() select new Dictionary<string, object>().ToDictionary(o => o.Key, o => o.Value)) 
+0

S'il vous plaît poster votre exception. – Robaticus

Répondre

3

Essayez

Data = entry.Elements().ToDictionary(e => e.Name.ToString(), e => e.Value); 
+0

+1 après la correction ;-) - vous étiez en premier. – BrokenGlass

+0

Fonctionne mais seulement si je change mon dictionnaire de en Achilleterzo

3

Je soupçonne ce que vous voulez vraiment est:

Dictionary<string,string> data = (from element in entry.Elements() select element) 
            .ToDictionary(x => x.Name.ToString(), x => x.Value); 

ou moins:

Dictionary<string,string> data = entry.Elements() 
             .ToDictionary(x => x.Name.ToString(), 
                x => x.Value);