Linq对XML的条件输出

时间:2016-11-03 23:30:08

标签: c# xml linq 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>

现在,我需要选择来自“帐户”Employee的{​​{1}}个元素。如果Department中没有,那么我需要从Account中选择Employee元素。 我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

作为选项,您可以使用以下代码:

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

答案 1 :(得分:0)

你可以这样做,这不是最优雅的方式。只需使用||并执行FirstOrDefault

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

答案 2 :(得分:0)

结合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"));

如果您不想使用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();

对于这些部门的所有员工:

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