2016-11-03 43 views
4

下面是我试图使用LINQ to XML来读取XML示例:条件输出通过LINQ到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元件,其从 “帐户” Department。如果Account中没有,那么我需要从Finance中挑选Employee元素。 我该怎么做?

+3

你有一些代码了吗? – DavidG

回答

0

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

var result = doc.Root.Descendants("Employee"). 
       Where(x => x.Element("Department").Value == "Account" || x.Element("Department").Value == "Finance"). 
       FirstOrDefault(); 
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(); 
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();