2016-11-03 49 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();