题
想要查询下面的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();
只返回:标题值
我想要的是在同一个查询中也返回持续时间值。
如何实现这一目标。
由于
解决方案
目前,您正在选择属性而不是元素。要包含持续时间,您需要整个元素。
var list = xd.Descendants("product")
.Select(element => new
{ Title = element.Attribute("title").Value,
Duration = element.Element("duration").Value })
.ToList();
(请注意,这不会进行任何类型的错误检查 - 最好是title属性和duration元素......)
其他提示
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();
不隶属于 StackOverflow