webworm
webworm

Reputation: 11019

LINQ to XML using Lambda syntax to populate object collection

I am trying to use LINQ with lambda syntax to load a List of objects from an XML fragment but I am having trouble with the lambda syntax in creating the new object.

Here is the custom class that will hold the data:

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

Here is the sample XML I am trying to load the object collection from:

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

I have tried using code such as the following but I know it is not correct as even intellisense in Visual Studio is going all "red squiggly line". In this example xml is an XDocument object that has loaded the XML listed above.

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

Upvotes: 0

Views: 57

Answers (1)

har07
har07

Reputation: 89285

x in the context of your Select() references individual physician element so you can't get degree attribute directly from x. You need to get the child lastname element first :

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

Also, all the "red squiggly line" are probably because the 3 fields visibility are private (default visibility) so it won't be accessible from outside of the class PhysicianInfoModel, though I can't be sure if this is the case since you didn't post the actual error message.

Upvotes: 1

Related Questions