2011-03-18 55 views
1

在代码中,我需要解析一个XML并获得一种ContactData。 我的目标是解析代码中显示的简单联系人列表,但不指定结构数据,如注释代码。Xml,Linq到类

,如果我尝试如果我使用 只有下面的代码使用注释代码我得到一个例外是不会发生:

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

如何纠正呢?

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

请发表您的例外。 – Robaticus 2011-03-18 17:14:23

回答

3

尝试

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

修复后的+1 ;-) - 你是第一个。 – BrokenGlass 2011-03-18 17:42:28

+0

正在工作,但只有当我将字典从<字符串,对象>更改为<字符串,字符串> – Achilleterzo 2011-03-21 08:40:41

3

我怀疑你真正想要的是:

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

或更短:

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