2008-03-19

How to retrieve XML content as it is provided by RSS feeds with Java

With the following minimalistic sample method you can retrieve XML code by providing just the URL of the corresponding XML source. In this particular case the title of every news item of the NetBeans RSS feed is printed by the "println" method of the "PrintWriter" class:

public static void getXmlContent(PrintWriter out) throws IOException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringElementContentWhitespace(true);
        factory.setIgnoringComments(true);
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.parse("http://www.netbeans.org/rss-091.xml");

        NodeList nodes = doc.getElementsByTagName("title");
        for (int j = 0; j < nodes.getLength(); j++) {
            Node n = nodes.item(j);
            if (n.getNodeName().equals("title")) {
                out.println(j + ". News Item Title: " + n.getTextContent() + "<br  />");
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
    }
}