LINQ to XML使用Lambda语法填充对象集合

时间:2017-10-24 23:05:40

标签: lambda linq-to-xml

我正在尝试使用带有lambda语法的LINQ从XML片段加载对象列表,但是我在创建新对象时遇到lambda语法问题。

以下是保存数据的自定义类:

public class PhysicianInfoModel
{
  string FirstName;
  string LastName;
  string Degree;
}

以下是我尝试加载对象集合的示例XML:

<response>
  <control>
    <status>success</status>
    <dtdversion>3.0</dtdversion>
  </control>
  <operation>
    <authentication>
      <status>success</status>
      <userid>jsmith</userid>
    </authentication>
    <result>
      <status>success</status>
      <physicianlist>
        <physician>
          <lastname degree="MD">Smith</lastname>
          <firstname>Paul</firstname>
        </physician>
        <physician>
          <lastname degree="DO">Smith</lastname>
          <firstname>Paul</firstname>
        </physician>
      </physicianlist>
    </result>
  </operation>
</response>

我尝试使用如下代码,但我知道这是不正确的,因为即使是Visual Studio中的intellisense也会出现所有“红色波浪线”。在此示例中,xml是一个XDocument对象,它已加载上面列出的XML。

List<PhysicianInfoModel> nodeList = xml.Descendants("physicianlist")
                                .Descendants("physician")
                                .Select(x => new PhysicianInfoModel()
                                {
                                  FirstName = x.?????,
                                  LastName = x.????,
                                  Degree = x.Attribute("degree") // Not working
                                });

1 个答案:

答案 0 :(得分:1)

x引用个人Select()元素的上下文中

physician,因此您无法直接从degree获取x属性。您需要先获取子lastname元素:

List<PhysicianInfoModel> nodeList = 
            xml.Descendants("physicianlist")
               .Descendants("physician")
               .Select(x => new PhysicianInfoModel()
               {
                   FirstName = (string)x.Element("firstname"),
                   LastName = (string)x.Element("lastname"),
                   Degree = (string)x.Element("lastname").Attribute("degree")
               })
               .ToList();

此外,所有“红色波浪线”都可能是,因为3个字段的可见性为privatedefault visibility)所以它won't be accessible from outside of the class {{1}虽然我不能确定是否是这种情况,因为你没有发布实际的错误信息。