2009-04-29 125 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();