HTML and CSS Reference
In-Depth Information
In your parser, the first thing you want to do is select all the item elements and then loop through
them to extract specific information, such as the title, description, a link to the source, and perhaps a
category. The following code selects all the item elements from the entire XML document.
var items = response.responseXML.querySelectorAll("rss > channel > item");
The query syntax is nearly identical to the CSS query syntax you discovered in Chapter 3, “Making
sense of CSS”: it means “get me all the elements named item that are children of the rss and channel
elements.” Next, you create a for-each loop and work on each item individually. As an example, the
following code shows how to retrieve the title of the first published news item.
var title = items[0].querySelector("title").textContent;
The final problem to solve, as far as parsing is concerned, is determining where you will store
parsed data. Ideally, you might want to gather information in an easy-to-manage array that you can
then bind to the list view. Here's the final version of the code for the parser:
rssReaderApp.parseFeed = function (response) {
if (response.responseXML == null) {
rssReaderApp.alert("Invalid data");
var items = response.responseXML.querySelectorAll("rss > channel > item");
for (var n = 0; n < items.length; n++) {
var newsElement = {};
newsElement.title = items[n].querySelector("title").textContent; = items[n].querySelector("link").textContent;
newsElement.guid = items[n].querySelector("guid").textContent;
newsElement.pubDate = items[n].querySelector("pubDate").textContent;
newsElement.description = items[n].querySelector("description").textContent;
// Check category
var category = "[No category]";
if (items[n].querySelector("category") != null)
category = items[n].querySelector("category").textContent;
newsElement.category = category;
There are a couple of things to note. First, if you're working with one specific RSS feed then you can
adapt your code to the expected format. If you instead plan to write a rather generic RSS Reader that
users can configure to get data from a variety of different sources, then you should pay attention to
each and every piece of data you try to access. For example, you'll find the category node in the Google
Search WWH ::

Custom Search