【发布时间】:2011-03-18 17:08:01
【问题描述】:
在代码中,我需要解析一个 xml 并获取一种 ContactData。 我的目标是解析一个简单的联系人列表,如代码所示,但不指定结构数据,如注释代码。
如果我尝试使用注释代码,我会得到一个异常,如果我使用它就不会发生 只有下面的代码:
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))
【问题讨论】: