Search code examples
linq-to-xmlxelement

Select from XElement with where statement using linq


I have and XElement object that was built up from an XML looking like this:

<Root>
  <Oppurtunities>
    <Oppurtunity>
      <Title> Account Manager</Title>
      <Company>Company name</Company>
      <Location>Boston</Location>
      <EndDate>2013-04-11</EndDate>
      <c>acce</c>
      <id>MNYN-95ZL8L</id>
      <Description>This is a detailed description...</Description>
    </Oppurtunity>

Now I need to get the description value from a specific Oppurtunity node, meaning I want to get description from where the id is specific. I need to do something like this:

//My XElement object is called oppurtunities
oppurtunities = new XElement((XElement)Cache["Oppurtunities"]);

string id = Request.QueryString["id"];

//I want to do something like this but of course this is not working
var description = (from job in oppurtunities
                              .Element("Oppurtunities")
                              .Element("Oppurtunity")
                              .Element("Description")
                              where job.Element("id") == id).SingleOrDefault();

Solution

  • You have to move .Element("Description") further in your query, to allow id condition work:

    //I want to do something like this but of course this is not working
    var description = (from job in oppurtunities
                                  .Element("Oppurtunities")
                                  .Elements("Oppurtunity")
                       where job.Element("id") == id
                       select job.Element("Description")).SingleOrDefault()
    

    To compare Element("id") as a string use (string)XElement conversion - it's gonna work even when <id> won't be found:

    where (string)job.Element("id") == id
    

    Using XElement.Value will throw NullReferenceException in that situation.