【问题标题】:Conditional Output by Linq to XMLLinq 到 XML 的条件输出
【发布时间】:2016-11-03 23:30:08
【问题描述】:

下面是我尝试使用 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>

现在,我需要选择来自“帐户”DepartmentEmployee 元素。如果Account 中没有,那么我需要从Finance 中选择Employee 元素。 我该怎么做?

【问题讨论】:

  • 你已经有一些代码了吗?

标签: c# xml linq linq-to-xml


【解决方案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();

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-19
        • 2015-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多