Downloading RSS Feeds
Very often, you need to download XML files and parse the contents (a good example of this is consuming web services). And so in this section, you will learn how to download a RSS feed and then extract the relevant parts (such as the <title>
element) and display its content.
|Figure 4. An Example: The "<item>/<title>" element contains the title of each posting.|
Define the DownloadRSS() function as shown in Listing 5.
First, call the OpenHttpConnnection() function to obtain an InputStream object. To process XML documents, use the following classes:
- Document: This represents an XML document.
- DocumentBuilder: This converts a XML source (such as files, streams, and so on) into a Document.
- DocumentBuilderFactory: This provides a factory for DocumentBuilder instances.
Essentially, the InputStream
object is used to read the XML data and then parsed into a Document
After the XML document is loaded into a Document object, you locate the relevant elements to extract. In particular, for an RSS document, the "<item>/<title>" element contains the title of each posting (see Figure 4).
|Figure 5. The RSS Feed: Displaying all the titles of the postings in a RSS feed using the Toast class.|
Once the title of each posting is retrieved, it is displayed using the Toast class.
To test the DownloadRSS() function, modify the onCreate() event as shown in Listing 6.
Press F11 in Eclipse to test the application on the Android emulator. Figure 5 shows the titles of all the postings contained within the RSS feed displayed by the Toast class.
That’s it! If you have interesting ideas involving things you can do with HTTP downloads, send me an email.