开发者

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;


How about this:

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


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


Try this:

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


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


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;


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜