1

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

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
Sreedhar
  • 29,307
  • 34
  • 118
  • 188

2 Answers2

2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @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 would it fail gracefully passing back a null, or would it blow up – Eoin Campbell Apr 29 '09 at 10:31
  • @jon skeet: doh!... missed your last line of the answer. – Eoin Campbell Apr 29 '09 at 10:32
  • 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 Apr 29 '09 at 10:33
  • element.Attribute("title") => resharper justs => possible 'System.NullReferenceException' – Sreedhar Apr 29 '09 at 10:34
  • How can this be written in VB.net – Sreedhar Apr 29 '09 at 10:38
  • I suspect the VB.NET code is *almost* identical, but I don't know offhand the anonymous type or lambda expression syntax... – Jon Skeet Apr 29 '09 at 10:43
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();
Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157