Posts Tagged ‘client-side xml parsing’

Using Google Feed API to parse external RSS/XML feeds

Tuesday, November 8th, 2011

Recently, I have been tasked to parse an XML/RSS feed using only client-side code. As the website is being migrated from Apache to IIS, it is difficult to settle on which server-side code to use (asp.net or php or python) thus the reasoning behind using pure Javascript/jquery for the task. At first, I thought that this was not possible but as I later found out . . . Google has released an API that would accomplish this task.

Here is a simple implementation of this task:

<script type="text/javascript" src="https://www.google.com/jsapi?key=API_KEY"></script><script type="text/javascript">// <![CDATA[
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("FEED_URL");
feed.setNumEntries(5);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("listing");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var li = document.createElement("span");
li.innerHTML = '<h3><a href="' + entry.link + '">' + entry.title + '</a> <cite>on ' + entry.publishedDate + '</cite></h3>';
li.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(li);
}
if(result.feed.entries.length == 0) { container.innerHTML = '<h4>Nothing in the feed.</h4> Please check back later'; }
} else {
var container = document.getElementById("listing");
container.innerHTML = '<span><h4>Error getting the feed.</h4>
<a href="http://www.benjamingaw.com/blog">Check out my Blog</a></li>';
}
});
}
// ]]></script>

In the HTML, all you need is a placeholder where you want your feed to appear:

You will need to sign up for an API key here. Google loads up the feed as a JSON object, but you can specify XML if that is what you prefer – the entire documentation is found here – http://code.google.com/apis/feed/v1/devguide.html

Look at a demo of this.
There are a couple of jquery plug-ins that take advantage of the Google API as well – go check out PaRSS and gfeed.