FDApple
FDApple

Reputation: 3

LINQ to XML Select Nodes by duplicate child node attributes

Need to pull out the Employees who have a pager.


<Employees>
  <Employee>
    <Name>Michael</Name>    
    <Phone Type="Home">423-555-0124</Phone>
    <Phone Type="Work">800-555-0545</Phone>
    <Phone Type="Mobile">424-555-0546</Phone>
    <Phone Type="Cell">424-555-0547</Phone>
    <Phone Type="Pager">424-555-0548</Phone>
  </Employee>
 <Employee>
    <Name>Jannet</Name>    
    <Phone Type="Home">423-555-0091</Phone>
    <Phone Type="Work">800-555-0545</Phone>
  </Employee>
</Employees>

I've got LINQ to get all the Phone nodes that have a pager and I can get all the employees. I can't wrap my head aroud drilling down to the phone node but still selecting the employee node?


var data = XElement.Load(@"employee.XML" );
var whoHasPager = from teamMember in data.Elements("Employee")
                where (string)teamMember.Element("Phone").Attribute("Type") == "Pager"
                select teamMember;

Upvotes: 0

Views: 1503

Answers (6)

James Kovacs
James Kovacs

Reputation: 11661

Try this:

var whoHasPager = from teamMember in data.Elements("Employee")
                  where teamMember.Elements("Phone").Any(x => x.Attribute("Type").Value == "Pager")
                  select teamMember;

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

var whoHasPager = doc.XPathSelectElements(
    "//Employee/Phone[@Type = 'Pager']/.."
);

Upvotes: 0

Brian R. Bondy
Brian R. Bondy

Reputation: 347416

The problem is that .Element will return the first element and not all of them of type Phone.

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

You could try using an XPath expression:

var data = XElement.Load(@"employee.XML" );
var whoHasPager =
    from teamMember in data.Elements("Employee")
    where teamMember.XPathSelectElement("Phone[@Type='Pager']") != null
    select teamMember;

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156624

How about this:

var whoHasPager = from teamMember in data.Elements("Employee")
                where teamMember.Elements("Phone").Any(
                    p => p.Attribute("Type").Value == "Pager")
                select teamMember;

Upvotes: 1

Pacane
Pacane

Reputation: 21491

You should see it as an SQL Statement maybe

SELECT employee from Employees where Phone Type='Pager'

therefore, the from statement should be Employees... Note: I'm not really good in LINQ, but I think the idea is the same...

Upvotes: 0

Related Questions