XML DOM Parsing in Java PRO

JAXP (Java API for XML) provides us with the capability to parse XML documents using a DOM parser.

The following code sample shows a simple parsing using the JAXP DOM parser.

package com.abelski.samples;

import java.io.IOException;
import java.net.URL;
import java.io.InputStream;
import java.net.HttpURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Sample
{
    public static void main(String args[])
    {
        InputStream is = null;
        HttpURLConnection con = null;
        try
        {
            URL url = new URL("https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=lifemichael");
            con = (HttpURLConnection)url.openConnection();
            con.setRequestMethod("GET");
            con.connect();
            is = con.getInputStream();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(is);
            NodeList list = doc.getElementsByTagName("text");
            int length = list.getLength();
            for(int i=0; i<length; i++)
            {
                System.out.println("\n\n"+
                    list.item(i).getFirstChild().getNodeValue());;
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch(ParserConfigurationException e)
        {
            e.printStackTrace();
        }
        catch(SAXException e)
        {
            e.printStackTrace();
        }
        finally
        {
          if(is!=null)
          {
              try
              {
                  is.close();
              }
              catch(IOException e)
              {
                  e.printStackTrace();
              }
          }
          if(con!=null)
          {
              con.disconnect();
          }
        }
    }
}

The following video clip provides more explanation while overviewing the code sample and showing its execution.

Share:

The Visitor Design Pattern

The Visitor Design Pattern

The visitor design pattern allows us to add operations to objects that already exist without modifying their classes and without extending them.

The Beauty of Code

Coding is Art! Developing Code That Works is Simple. Develop Code with Style is a Challenge!

Update cookies preferences