Reputation: 3
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
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
Reputation: 1039130
var whoHasPager = doc.XPathSelectElements(
"//Employee/Phone[@Type = 'Pager']/.."
);
Upvotes: 0
Reputation: 347416
The problem is that .Element
will return the first element and not all of them of type Phone.
Upvotes: 1
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
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
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