下面是我尝试使用
Linq to
XML读取的示例
XML:
<root>
<Employee>
<Name>Jeff</Name>
<Department>Account</Department>
</Employee>
<Employee>
<Name>David</Name>
<Department>Finance</Department>
</Employee>
<Employee>
<Name>Neil</Name>
<Department>Sales</Department>
</Employee>
<Employee>
<Name>Jason</Name>
<Department>Retail</Department>
</Employee>
</root>
现在,我需要选择来自“帐户”部门的员工元素.如果账户中没有,那么我需要从财务中选择员工元素.
我怎样才能做到这一点?
最佳答案 作为选项,您可以使用此代码:
var result = XElement.Parse(xml).Descendants("Employee")
.GroupBy(x => x.Element("Department").Value)
.OrderByDescending(x=>x.Key=="Account")
.FirstOrDefault(x => (x.Key == "Account" && x.Count() > 0) ||
x.Key == "Finance").ToList();