【问题标题】:Xml, Linq to ClassXml,Linq to Class
【发布时间】: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))

【问题讨论】:

    标签: .net xml linq c#-4.0


    【解决方案1】:

    试试

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

    【讨论】:

    • 正在工作,但前提是我将字典从 更改为
    【解决方案2】:

    我怀疑你真正想要的是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多