views:

78

answers:

2

want to query below 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>

for now am doing something below:

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

which returns just : title value

What i want is in same query to return Duration value too.

How can this be achieved.

Thanks

+1  A: 

Currently you're selecting the attributes instead of the elements. To include the duration, you'll need the whole element.

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

(Note that this doesn't do any sort of error checking - there'd better be a title attribute and a duration element...)

Jon Skeet
@jon skeet: do you need to do null checks within the Linq/Lambda statements if theres a possible jagged structure to the XML. i.e. if there wasn't necessarily an `Element("duration")` below <product> would it fail gracefully passing back a null, or would it blow up
Eoin Campbell
Thanks this sorted out.
Nev_Rahd
@jon skeet: doh!... missed your last line of the answer.
Eoin Campbell
It might not have been there when you first read the answer... I may well have been editing at the time :) However, I tend to think that if I've got an XML document with an expected structure, throwing an exception may well more appropriate than providing a default value... better to know the data is invalid than pretend it isn't. Admittedly the NRE here wouldn't be the friendliest error report in the world...
Jon Skeet
element.Attribute("title") => resharper justs => possible 'System.NullReferenceException'
Nev_Rahd
How can this be written in VB.net
Nev_Rahd
I suspect the VB.NET code is *almost* identical, but I don't know offhand the anonymous type or lambda expression syntax...
Jon Skeet
A: 
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();
Eoin Campbell
What the syntax for this VB.net
Nev_Rahd