Friday, March 13, 2009

NIH Funding-Part 2:Reading an RSS Feed in Java

In Part 1, I showed how to write an RSS Feed. Here I show how to use Java to read an RSS feed from the NIH link at http://grants.nih.gov/grants/guide/newsfeed/fundingopps.xml .

Step 1: The RSS Reader and Testing the Code

public class XmlRSSReader
{
public XmlRSSReader() {
try {
Builder bd = new Builder();
Document doc = bd.build("fundingopps.xml");
// Get the file's root element
Element root = doc.getRootElement();
Element channel = doc.getFirstChildElement("channel");
// Get its title element
Element title = channel.getFirstChildElement("title");
Text titleText = (Text)title.getChild(0);
Elements NIHs = root.getChildElements("item");
for (int i = 0; i < NIHs.size(); i++)
Element NIH = NIHs.get(i);
// Look for a title element inside it
Element itemTitle = NIH.getFirstChildElement("title");
// If found, look for its contents
if (itemTitle != null) {
Text itemTitleText = (Text) itemTitle.getChild(0);
// Good place to search the text
// do something
if (itemTitleText.toString().indexOf(searchTerm) == -1)
//do something
}
// Get all child elements of
Elements children = NIH.getChildElements();
for (int j = 0; j < children.size(); j++) {
Element child = children.get(j);
Text childText = (Text) child.getChild(0);
if (childText != null) {
System.out.print(child.getLocalName());
System.out.print(": ");
System.out.print(childText.getValue());
System.out.println("");
}

Step 2: Test the Code

public static void main(String[] arguments) {
XmlRSSReader xrss = new XmlRSSReader();
}
}

Clearly, we can combine RSS feeds and search for items on elements such as titles to build lists of common funding opportunities to reseachers.

No comments: