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.

<root>
  <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>
  <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>
  <ul class="connectedSortable ui-sortable" tid="1159">
    <li class="termName">Spring 2011</li>
  </ul>
</root>

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

}
Advertisements

One thought on “Reading XML with C#, XDocument, and Linq

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s