XPath Query Example in Java

Connect with

XPath Query Example in JavaIn this article of XPath Query Example in Java, how to write your query on any XML using Java XPATH example.

1. Overview of XPATH Query example in Java

XPath is basically used for Querying on a particular XML similar to SQL queries on any particular table.

XPath is a powerful query language which is basically used for query on XML. This is the most widely used parser and querying on XML.
This example is tested with JDK 7 and Eclipse Luna on the Window 64-bit platform. However, this will run on any platform on any IDE and any JDK ( > 1.6).
XPath expression specifies a pattern that selects a set of XML nodes. XSLT templates then use those patterns when applying transformations. XPointer, on the other hand, adds mechanisms for defining a point or a range so that XPath expressions can be used for addressing).

2. XPath Addressing syntax

In general , when you carefully observed, an XML document is a tree-structured (hierarchical structure) collection of nodes. In a hierarchical directory structure, it is useful to specify a path that points to a particular node in the hierarchy, therefore you can say that name of the specification: XPath. some key point of directory path:

  • The forward slash (/) is used as a path separator.
  • An absolute path from the root of the document starts with a /.
  • A relative path from a given location starts with anything else.
  • A double period (..) indicates the parent of the current node.
  • A single period (.) indicates the current node.

3. Sample XML file for Java XPATH example

Following is the xml file for Java XPATH example , where we write the xpath query to read different things.

File: person.xml
For simplicity, keep this file i.e. person.xml in the same location where your program will be.

    New Delhi

4. Java Class to Query using XPath

package com.mysoftkey.xpath;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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;

 * this java program is used for XPath Query Example step by step with different
 * scenario.
 * @author ranjeet.jha
public class XpathQueryExample {

 // for simplicity keep person.xml in same folder location where this class is.
 private static final String fileName = "./src/com/mysoftkey/xpath/person.xml";

 public static void main(String[] args) {
  try {
   // standard way for reading an XML file
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder;
   Document doc = null;
   XPathExpression expr = null;
   builder = factory.newDocumentBuilder();
   doc = builder.parse(fileName);

   // create an XPathFactory
   XPathFactory xFactory = XPathFactory.newInstance();

   // create an XPath object
   XPath xpath = xFactory.newXPath();

   // compile the XPath expression
   expr = xpath.compile("//person[firstName='Anushka']/lastName/text()");
   // run the query and get a nodeset
   Object result = expr.evaluate(doc, XPathConstants.NODESET);

   // cast the result to a DOM NodeList
   NodeList nodes = (NodeList) result;
   for (int i = 0; i < nodes.getLength(); i++) {

   // new XPath expression to get the number of people with name Lars
   expr = xpath.compile("count(//person[firstName='Shakti'])");

   // run the query and get the number of nodes
   Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER);
   System.out.println(" [count(//person[firstName='Shakti'])] : " + number);

   // do we have more than 1 people with name Shakti?
   expr = xpath.compile("count(//person[firstName='Shakti']) >1");

   // run the query and get the number of nodes
   Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
   System.out.println("count(//person[firstName='Shakti']) >1 is : " + check);

  } catch (XPathExpressionException | ParserConfigurationException 
    | SAXException | IOException e) {


5. Output the program

Number of objects [count(//person[firstName='Shakti'])] : 2.0
count(//person[firstName='Shakti']) >1 is : true
first name by id [2] : Shakti
get list of person first name whose age greater than 25 as:  

6. Examples of Utility method

It’s better to write a method and for each query and call that method wherever you required like as.

call function from main method

// get person first name by person id
   String firstNames = getPersonFirstNameById(doc, xpath, 2);
   System.out.println("first name by id [2] : " + firstNames);

utility method

  * This method is used to get person's first name by person id.
  * @param doc
  * @param xpath
  * @param id
  * @return
 private static String getPersonFirstNameById(Document doc, XPath xpath, int id) {
  String name = null;
  try {
   XPathExpression expr = xpath.compile("/persons/person[@id='" + id + "']/firstName/text()");
   name = (String) expr.evaluate(doc, XPathConstants.STRING);
  } catch (XPathExpressionException e) {

  return name;

Utility method to get list of First name of person for age greater than the provided age.

  * This method return all first name list whose age is greater than provided
  * age.
  * @param doc
  * @param xpath
  * @param age
  * @return
 private static List getPersonFirstNameWithAge(Document doc, XPath xpath, int age) {
  List list = new ArrayList<>();
  try {
   XPathExpression expr = xpath.compile("/persons/person[age>" + age + "]/firstName/text()");
   NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
   for (int i = 0; i < nodes.getLength(); i++)
  } catch (XPathExpressionException e) {
  return list;

Call above function i.e. getPersonFirstNameWithAge() from main method to get list of firstName.

   // get list of person first name whose age greater than 25.
   List firstNameList = getPersonFirstNameWithAge(doc, xpath, 25);
   System.out.println("get list of firstName whose age greater than 25:  ");
   for (String fname : firstNameList) {

7. Related Post on Parser

In order to understand the difference aspect of XML parsers, you have to understand each one of the parsers. For this you can visit.

8. Reference

You can visit Oracle Java site for more details.

Thanks for visiting this post for the Java XPATH example. You can also visit Core Java Tutorial Listing page for more articles on Core Java.
Your comments are welcome to improve this post. Happy Learning! 🙂

Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *