1

Given the XML below I need to recurively select the employee who's positions.position.manager_position matches a position parameter.

How can this be achieved with linq to XML?

<employee id="0004000">
    <!-- ... -->
</employee>
<employee id="0004001">
     <username>Administrator</username>
     <positions>
      <position id="00008001" isPrimary="1">
       <title>GENERAL MANAGER</title>
       <manager_position>00008431</manager_position>
      </position>
     </positions>
</employee>
<employee id="0004002">
    <!-- ... -->
</employee>
Burt
  • 7,680
  • 18
  • 71
  • 127

2 Answers2

1

You could do it like this:

employees.Where(e => e.Element("positions")
                      .Elements("position")
                      .Elements("manager_position")
                      .Any(mp => mp.Value == position))

Select those employees, that have at least one manager_position element that matches the posution you're looking for.

svick
  • 236,525
  • 50
  • 385
  • 514
1

This example will return the matching employee XElement or null when none were found:

var employees = XElement.Parse(
    "<employees><employee><!-- ... --></employee></employees>");

var results = employees
    .Elements("employee")
    .Where(e => e.Descendants("manager_position").Value == "00008431")
    .SingleOrDefault();

See also:

Enrico Campidoglio
  • 56,676
  • 12
  • 126
  • 154