Reading XML with C#, XDocument, and Linq

The sample code below uses the XDocument class in combination with Linq to read some XML. I liked the combo enough to want to remember it in the future, hence this post.

Say you had the following XML assigned to the termsXml string variable.

  <ul class="connectedSortable ui-sortable" tid="1146">
    <li class="termName">Fall 2010</li>
    <li class="course" cid="2826" style="">FAC101: Art Appreciation</li>
    <li class="course" cid="2827" style="">CSC105: Using Modern Operating Systems</li>
    <li class="course" cid="2828" style="">CSC110: Introduction to Computer Science</li>
  <ul class="connectedSortable ui-sortable" tid="1156">
    <li class="termName">Winter 2011</li>
    <li class="course" cid="2829" style="">FAC105: Leadership and Problem Solving</li>
  <ul class="connectedSortable ui-sortable" tid="1159">
    <li class="termName">Spring 2011</li>

You would read it with this C# code:

var reader = new StringReader(termsXml);
var xdoc = XDocument.Load(reader);

var terms = from term in xdoc.Descendants("ul")
            select new
                TermId = term.Attribute("tid").Value,
                Courses = term.Descendants("li")

foreach (var term in terms)
    var courseIds = (from course in term.Courses
                        where course.Attribute("cid") != null
                        select course.Attribute("cid").Value).ToList();
    // do stuff with the courseids here