indiWiz.com

Subhash's Tech Log

XPath in Java: Code Snippet

without comments

try{
    InputStream is = ...;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(is);
    is.close();

    XPathFactory xfactory = XPathFactory.newInstance();
    XPath xpath = xfactory.newXPath();
    XPathExpression xpr = xpath.compile("/executors/executor");

    NodeList nodes = (NodeList)xpr.evaluate(doc, XPathConstants.NODESET);
    int size = nodes.getLength();
    for(int i=0; i<size; i++){
        NamedNodeMap nnm = nodes.item(i).getAttributes();
        String strPath = nnm.getNamedItem("path").getNodeValue();
        String strClass = nnm.getNamedItem("class").getNodeValue();
        print("Path / Class: " + strPath + " / " + strClass);
    }
} catch(ParserConfigurationException ex){
    print(ex.getMessage());
} catch(SAXException ex){
    print(ex.getMessage());
} catch(IOException ex){
    print(ex.getMessage());
} catch(XPathExpressionException ex){
    print(ex.getMessage());
}

Written by Subhash Chandran

April 25th, 2009 at 10:11 am

Posted in Java

Tagged with , ,

Leave a Reply