XPath Query Example in Java

Connect with

Oracle Java
In this post, I tried to demonstrate how to write your query on any xml. XPath is basically used for Querying on a particular XML similar like SQL query on any particular database.

XPath is a powerful query language which is basically used for query on XML. This is most widely used parser and querying on XML.

This example is tested with JDK 7 and Eclipse Luna on 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).

1. 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.

2. Sample XML file

Following is the xml file 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.



  
    Anushka
    Jha
    New Delhi
    30
  
  
    Shakti
    Yadav
    Gurgaon
    30
  
  
    Swati
    Nagpal
    Bombay
    19
  
  
    Shakti
    Singh
    Chennai
    35
  
  
 

3. 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();
   factory.setNamespaceAware(true);
   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++) {
    System.out.println(nodes.item(i).getNodeValue());
   }

   // 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) {
   e.printStackTrace();
  }
 }

}

4. Output the program:

Jha
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:  
Anushka
Shakti
Shakti

5. Examples of Utility method

It’s better 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 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) {
   e.printStackTrace();
  }

  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++)
    list.add(nodes.item(i).getNodeValue());
  } catch (XPathExpressionException e) {
   e.printStackTrace();
  }
  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) {
    System.out.println(fname);
   }

Reference:
Oracle Java site

Your comments are welcome to improve this post. Happy Learning 🙂


Connect with

Leave a Reply

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