Tuesday, September 27, 2011

Easy way to parse and read XML Data


Note : Required dom4j.jar

This Class file should be mandatory :


XMLHandler.java


import java.io.IOException;
import java.io.StringReader;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;




public class XMLHandler {


    private Document doc;


    public XMLHandler(final String message) throws IOException, SAXException, ParserConfigurationException {
        final StringReader response = new StringReader(message);
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new InputSource(response));
    }




    public final String getStringValue(final String xPath) throws XPathException {
        // Get the matching elements
        XPathFactory factory = XPathFactory.newInstance();
        XPath path = factory.newXPath();
        final Node node = (Node)path.evaluate(xPath, doc, XPathConstants.NODE);


        return node.getFirstChild().getNodeValue().trim();
    }






}




Eg :




public class Testing


{



 public String simple(String xml) throws IOException, SAXException, ParserConfigurationException, XPathException
    {
        String xmlresp=null;




        XMLHandler xmh=new XMLHandler(xml);
        System.out.println("res"+xmh);


        xmlresp=xmh.getStringValue("/xml/datacom-api-output/response/code");


        System.out.println("cuming here..result : "+xmlresp);




        return xmlresp.toString();


    }







public static void main(String[]a)
{


  Testing t=new Testing();



  String xmlfile="<xml><datacom-api-output><response><code>0</code></response></datacom-api-output></xml>";




String result=  t.sample(xmlfile);
sop("----------"+result);




}


}



















No comments:

Post a Comment