简体   繁体   English

Linq对XML的条件输出

[英]Conditional Output by Linq to XML

Below is the sample XML that I am trying to read using Linq to XML: 下面是我尝试使用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>

Now, I need to select Employee elements which are from "Account" Department . 现在,我需要选择来自“帐户” Department Employee元素。 If there are none in Account then I need to pick Employee element from Finance . 如果Account中没有,那么我需要从Finance选择Employee元素。 How can I do that? 我怎样才能做到这一点?

As an option you can use this code: 作为选项,您可以使用此代码:

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();

You can do this, it is not the most elegant way. 你可以做到这一点,它不是最优雅的方式。 Just use || 只需使用|| and take FirstOrDefault 并采取FirstOrDefault

 var result = doc.Root.Descendants("Employee").
               Where(x => x.Element("Department").Value == "Account" || x.Element("Department").Value == "Finance").
               FirstOrDefault();

Combining Linq and XPath you can do it like this: 结合Linq和XPath你可以这样做:

var document = XDocument.Load("data.xml").Root;
//Find a Department with a given value and retrieve its Employee parent
string xPath = "//Department[text() = '{0}']/parent::Employee";

//Search for "Account" Department. If nun was found will return null and then
//search for "Finance"
var employee = document.XPathSelectElement(string.Format(xPath, "Account")) ??
               document.XPathSelectElement(string.Format(xPath, "Finance"));

If you do not want to use XPath then you can do this: 如果您不想使用XPath,那么您可以这样做:

var employee = (from item in XDocument.Load("data.xml").Descendants("Employee")
                let department = item.Element("Department").Value
                orderby department == "Account" ? 1 :
                        department == "Finance" ? 2 : 3
                select item).FirstOrDefault();

For all employees of those departments: 对于这些部门的所有员工:

var employee = (from item in XDocument.Load("data.xml").Descendants("Employee")
                group item by item.Element("Department").Value into grouping
                orderby grouping.Key == "Account" ? 1 :
                        grouping.Key == "Finance" ? 2 : 3
                select grouping.ToList()).FirstOrDefault();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM