开发者

Xml, Linq to Class

As in the code, i need to parse an xml and get a type of ContactData. My goal is to parse a simple contact list like shown in the code, but without specify the structure data, like the commented code.

If i try to use the commented code i get an exception that not happen if i use only the code below:

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

How to correct this?

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


Try

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


I suspect what you really want is:

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

or shorter:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜