Sunday, September 10, 2017

XPath Example in Java

10 Example of XPATH
------------------------
package test;

import java.io.IOException;
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.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
  * Simple Java program to execute XPATH expression and retrieve value from XML documents
  */
public class XPathExample {

    public static void main(String[] args){
        try {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true);
         
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document doc = builder.parse("Books.xml");
         
         
            XPath xpath = XPathFactory.newInstance().newXPath();
         
            XPathExpression expr = xpath.compile("bookstore/book[@category='COOKING']/title/text() | bookstore/book[@category='WEB']/title/text()");

         
            Object result = expr.evaluate(doc, XPathConstants.NODESET);
         
         
            NodeList nodes = (NodeList) result;
            System.out.println("Result: " + nodes);
            for (int i = 0; i < nodes.getLength(); i++) {
                System.out.println(nodes.item(i).getNodeValue());
            }
         
        }catch (XPathExpressionException ex) {
            ex.printStackTrace();
        } catch (SAXException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException ex) {
            ex.printStackTrace();
        }
    }
}

That's all about how to use XPath in Java. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.