dom4j Example - Read XML from URL

Posted By: Matpal Media - 3:31 AM
dom4j provides a Java library for working with XML, XPath, and XSLT.

dom4j is an easy to use, open source library for working with XML, XPath, and XSLT on the Java platform, using the Java Collections Framework, and with full support for DOM, SAX, and JAXP.
Download dom4j from here

Here is the example of reading XML by dom4j from URL

import java.net.URL;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class foo {

public static void main(String args[])
{
 try {
           foo obj=new foo();
       URL myURL;
       
       myURL = new URL("http://twitter.com/users/hiteshmathpal");
       Document document=obj.parse(myURL);        
       Element root = document.getRootElement();
     
       for ( Iterator i = root.elementIterator(); i.hasNext(); ) 
           {
            Element row = (Element) i.next();
            Iterator itr = row.elementIterator();
            while(itr.hasNext())
                 {
                  Element child = (Element) itr.next();
                  //do what ever you want, I will just print
                  System.out.println("Element Name:"+child.getQualifiedName() );
                  System.out.println("Element Value:"+child.getText());
                  }
             }
         }  
        catch (Exception e) 
           {
            // TODO Auto-generated catch block
            e.printStackTrace();
            }
    
    }
    
    public Document parse(URL url) throws DocumentException 
    {
        SAXReader reader = new SAXReader();
        Document document = reader.read(url);
        return document;
    }
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.