需要拔出有寻呼机的员工。
<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>
我有LINQ来获取所有拥有寻呼机的Phone节点,我可以获得所有员工。我无法将我的脑袋包裹到电话节点,但仍然选择员工节点?
var data = XElement.Load(@"employee.XML" );
var whoHasPager = from teamMember in data.Elements("Employee")
where (string)teamMember.Element("Phone").Attribute("Type") == "Pager"
select teamMember;
答案 0 :(得分:1)
这个怎么样:
var whoHasPager = from teamMember in data.Elements("Employee")
where teamMember.Elements("Phone").Any(
p => p.Attribute("Type").Value == "Pager")
select teamMember;
答案 1 :(得分:1)
问题是.Element
将返回第一个元素,而不是所有类型的电话。
答案 2 :(得分:0)
您应该将其视为SQL语句
SELECT employee from Employees where Phone Type='Pager'
因此,from语句应该是Employees ... 注意:我在LINQ中并不是很擅长,但我认为这个想法是一样的......
答案 3 :(得分:0)
您可以尝试使用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;
答案 4 :(得分:0)
var whoHasPager = doc.XPathSelectElements(
"//Employee/Phone[@Type = 'Pager']/.."
);
答案 5 :(得分:0)
试试这个:
var whoHasPager = from teamMember in data.Elements("Employee")
where teamMember.Elements("Phone").Any(x => x.Attribute("Type").Value == "Pager")
select teamMember;