Thursday, April 5, 2012

Parsing XML with : in the name

When parsing XML in C#, problems arise when XML contains a colon (:).  For example, the start of last.fm's resulting XML when performing a search looks like this:


<results xmlns:opensearch="http://a9.com/-/spec/opensearch/1.1/" for="tsin-tsi">
<opensearch:Query role="request" searchTerms="tsin-tsi" startPage="1"/>
<opensearch:totalResults>43</opensearch:totalResults>
<opensearch:startIndex>0</opensearch:startIndex>
<opensearch:itemsPerPage>30</opensearch:itemsPerPage>

It turns out that these "opensearch" elements are actually part of the opensearch namespace.  It might not seem relevant for a text-based result file like XML, but it is - you have to declare that namespace before you can grab the totalResults, startIndex or itemsPerPage.  To get the number of results, I used this code:

XNamespace opensearch = "http://a9.com/-/spec/opensearch/1.1/";
XElement pagecount = doc.Descendants(opensearch + "totalResults").FirstOrDefault();
numberofResults = Convert.ToInt32(pagecount.Value);


No comments:

Post a Comment