Tuesday, May 16, 2023

How to Create and Evaluate XPath Expression in Java - Tutorial and Example

You can use XPathExpression from javax.xml.xpath package to create and execute XPATH expression in Java.  Java API provides javax.xml.xpath  package, which contains classes like Xpath, XpathFactory to work with XPATH and XML documents. By the way this is third article on Xpath, In last couple of tutorials e.g. XPATH examples to select values using attributes and my XPATH notes for Java programmer, we have seen basics of Xpath expression from XML and Java point of view.  Anyone who has work with XML technologies in Java knows importance of XPATH, it is one the most useful technology to retrieve selected data from XML files.

XPATH is like SQL which is used to retrieve data from relational database. Many back-office and middle-office Java application which transfers data in form of XML documents makes extensive use of  XPATH expression to retrieve value for printing or for decision making. 

Though there are lot of open source XML libraries are available to assist with Java and XML development e.g. XML Beans. I personally prefer to use standard Java API if  functionality is available there. 

In this Java the tutorial we will learn how to create XPath expression in Java program and retrieving values from XPATH e.g. text, numbers and boolean values, which is critical for programming flow.

How to Create and Evaluate XPath Expression in Java - Tutorial and Example




Java XPath expression Example

Java Xpath expression example create and evaluate Xpath in JavaCreating XPATH expression is simple, just navigate to the node you want to retrieve by putting "/" like in our example if we want to retrieve models of each smartphone than we will write Xpath expression as /smartphones/smartphone/model

Apart from navigating to the desired node in Xpath expression, we have also used utility method text() to retrieve text and count() to count the number of matching results. Java classes from java.xml.xpath package e.g. XPath, XPathFactory and XPathExpression is used to create and evaluate Xpath in Java programming language.




/**
 * Java program to demonstrate How to create XPATH expression, How to execute XPATH
 * expression to retrieve text value, numeric value and boolean value.
 * 
 */
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;


public class XPathExample {

    public void xPathProcessor() throws SAXException, IOException
                  ,  XPathExpressionException, ParserConfigurationException {

     
        //Create DocumentBuilderFactory for reading xml file
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();;
        Document doc = builder.parse("smartphone.xml");
     
        // Create XPathFactory for creating XPath Object
        XPathFactory xPathFactory = XPathFactory.newInstance();

        // Create XPath object from XPathFactory
        XPath xpath = xPathFactory.newXPath();

        // Compile the XPath expression for getting all brands
        XPathExpression xPathExpr = xpath.compile("/smartphones/smartphone/brand/text()");
     
        // XPath text example : executing xpath expression in java
        Object result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Java Xpath text example: All brands of popular smartphones ");
        printXpathResult(result);

        //get all models by xpath expression in java
        xPathExpr = xpath.compile("/smartphones/smartphone/model/text()");
        result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Java Xpath text example: All popular smartphone model ");
        printXpathResult(result);
     
        // XPath count example : XPath expression to count elements in xml
        xPathExpr = xpath.compile("count(/smartphones/smartphone)");
        Double count = (Double) xPathExpr.evaluate(doc, XPathConstants.NUMBER);
        System.out.println("XPath count example: How many Smartphones we have: ");
        System.out.println("Count of elements: " + count);

     
        // XPath conditional exampl e: Do we have any HTC smartphone
        xPathExpr = xpath.compile("count(/smartphones/smartphone[brand='HTC']) > 0");
        Boolean test = (Boolean) xPathExpr.evaluate(doc, XPathConstants.BOOLEAN);
        System.out.println("XPath boolean example: Do we have any HTC smartphone ");
        System.out.println(test);

    }
 
    public void printXpathResult(Object result){
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }
    }

    public static void main(String[] args) throws XpathExpressionException
               ,  ParserConfigurationException, SAXException, IOException {

        XPathExample xPathExample = new XPathExample();
        xPathExample.xPathProcessor();
    }
}

Output:
Java Xpath text example: All brands of popular smartphones
Apple
Samsung
Nokia

Java Xpath text example: All popular smartphone model
IPhone4S, IPhone4, IPhone5
Galaxy S2, Galaxy nexus, Galaxy Ace
Lumia 800, Lumia 710, Nokia N9
XPath count example: How many Smartphones we have:
Count of elements: 3.0
XPath boolean example: Do we have any HTC smartphone
False


That’s all on How to create and evaluate XPath expression in Java. We have seen How to select XML elements value as text using text() function and counted matching elements using count() function. Xpath is real interesting stuff and once you get the basics, it's very easy to work with Xpath both in XML editors and Java programming language.


Other Java and XML tutorials for Java programmers

3 comments:

  1. Great example Sir, There are not much tutorial in Java about working with Xpath and XSLT transformation. Love to see more from you in this topic.

    ReplyDelete
  2. Thank you so much for posting such kind of good tutorials in XPath. Very clear and elegant code!

    ReplyDelete
  3. Where is the XML file that you are parsing. It is also important to see the XML file structure.

    ReplyDelete