2009-04-29 123 views
1

要查詢以下XML的LINQ to XML

<courseList filedUnder="Courses"> 
    <category code="4wd" title="4wd Operation"> 
    <product code="lr" title="4wd Bush Driving"> 
     <duration>1 Day</duration> 
    </product> 
    <product code="hr" title="4wd Defensive Driving"> 
     <duration>1 Day</duration> 
    </product> 
    <product code="sr" title="Self-Recovery"> 
     <duration>1 Day</duration> 
    </product> 
    </category> 
</courseList> 

現在我下面做的事情:

 var list = (from x in xd.Descendants("product").Attributes("title") 
     select new { Title= x.Value}).ToList(); 

返回剛:標題值

我想是在相同的查詢也返回持續時間值。

這是如何實現的。

感謝

回答

2

您目前選擇屬性代替元素。要包含持續時間,您需要整個元素。

var list = xd.Descendants("product") 
      .Select(element => new 
       { Title = element.Attribute("title").Value, 
        Duration = element.Element("duration").Value }) 
      .ToList(); 

(請注意,這並不做任何類型的錯誤檢查的 - 有最好是一個title屬性和持續時間元素...)

+0

@喬恩雙向飛碟:你需要在Linq/Lambda語句中進行空檢查,如果這些檢查可能是XML的鋸齒結構。即如果不存在低於的元素(「持續時間」),它是否會優雅地傳回一個空值,否則它會炸掉 – 2009-04-29 10:31:16

+0

謝謝這樣整理。 – Sreedhar 2009-04-29 10:31:45

1
var list = (from x in xd.Descendants("product") 
      select new { 
       Title= x.Attribute("title") != null ? x.Attributes("title").Value : "", 
       Duration = x.Element("duration") != null ? x.Element("duration").Value : "" 
      } 
      ).ToList();