XPath

Java XPathConstants Example

In this example, we will be discussing about Java class XPathConstants with an example. Before we start with this article, it is expected that we have a basic understanding of XML. In brief, XML stands for eXtensible Markup Language, which is designed to store and transport data. It is both human and machine readable.

1. Introduction

XPath is a standard syntax recommended by the W3C.  XPath is a major element in the XSLT standard that can be used to navigate through expressions, elements and attributes in an XML document. XPath expressions help us to navigate to the desired node in an XML that we want to retrieve. javax.xml.xpath package provides XPath support in Java. Java classes from javax.xml.xpath package e.g. XPathXPathFactory , XPathConstants and XPathExpression are used to create and evaluate XPath in Java. Java XPath supported return types are defined in XPathConstants class. XPathConstants extends java.lang.Object class.

In this example, we will see how to use XPathConstants class. We will be using Eclipse Oxygen and Java version 1.8 to create our demo project for this example.

2. About XPathConstants class (i.e. XPath return types)

In java, An XPath expression may return one of following data types:

node-set: Represents a set of nodes. The set can be empty, or it can contain any number of nodes.

node (Java support it): Represents a single node. This can be empty, or it can contain any number of child nodes.

boolean: Represents the value true or false. Be aware that the true or false strings have no special meaning or value in XPath.

number: Represents a floating-point number. All numbers in XPath and XSLT are implemented as floating-point numbers; the integer (or int) datatype does not exist in XPath and XSLT. Specifically, all numbers are implemented as IEEE 754 floatingpoint numbers, the same standard used by the Java float and double primitive types. In addition to ordinary numbers, there are five special values for numbers: positive and negative infinity, positive and negative zero, and NaN, the special symbol for anything that is not a number.

string: Represents zero or more characters, as defined in the XML specification. These datatypes are usually simple, and with the exception of node-sets, converting between types is usually straightforward.

3. Demonstration

The supported return types in XPathConstants class listed below are demonstrated via a code example:

  • XPathConstants.STRING
  • XPathConstants.NUMBER
  • XPathConstants.BOOLEAN
  • XPathConstants.NODE
  • XPathConstants.NODESET

Lets create a java project to demonstrate all the supported return types.

3.1 Creating a java project

Create a new java project in eclipse using File -> New ->Java Project. Enter the project name as “XPathConstantsExample” and a new java project should get created. Refer to the screenshot below.

Fig 1: Creating Java Project

3.2 Creating a new XPathConstantsExample class

Create a new java class naming XPathConstantsExample.java, using right click on java project->New->Class.

Fig 2: Create new Java class

3.3 XPathConstantsExample.java

After creating a new class, refer to the code below for XPathConstantsExample.java.

XPathConstantsExample.java

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 XPathConstantsExample {

	public static void main(String[] args) {

		DocumentBuilderFactory factory;
		DocumentBuilder builder;
		try {
			// Create DocumentBuilderFactory for reading xml file
			factory = DocumentBuilderFactory.newInstance();
			builder = factory.newDocumentBuilder();
			Document doc = builder.parse("employee.xml");

			// Create XPathFactory for creating XPath Object
			XPathFactory xPathFactory = XPathFactory.newInstance();
			// Create XPath object from XPathFactory
			XPath xpath = xPathFactory.newXPath();

			// Method to demonstrate various XPathConstants
			demonstrateConstants(doc, xpath);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Method to demonstrate various XPathConstants
	 * 
	 * @param doc
	 * @param xpath
	 */
	private static void demonstrateConstants(Document doc, XPath xpath) {
		try {
			// 1. XPathConstants.STRING
			// Compile the XPath expression for getting a string value
			XPathExpression xPathExpr = xpath.compile("/Employees/Employee/name/text()");
			// XPath text example : executing xpath expression in java Object
			Object result = xPathExpr.evaluate(doc, XPathConstants.STRING);
			System.out.println("Java XpathConstants String example:::::" + result);

			// 2. XPathConstants.NUMBER
			// Compile the XPath expression for getting a number value
			xPathExpr = xpath.compile("/Employees/Employee/age");
			result = xPathExpr.evaluate(doc, XPathConstants.NUMBER);
			System.out.println("Java XpathConstants Number example:::::" + result);

			// 3. XPathConstants.BOOLEAN
			// Compile the XPath expression for getting a boolean value
			xPathExpr = xpath.compile("/Employees/Employee/fulltime");
			result = xPathExpr.evaluate(doc, XPathConstants.BOOLEAN);
			System.out.println("Java XpathConstants Boolean example:::::" + result);

			// 4. XPathConstants.NODESET
			// Compile the XPath expression for getting a NodeSet: Gets all name tag values from employee.xml	
			System.out.println("Java XpathConstants NODESET example:::::getting all nodes name attribute");
			xPathExpr = xpath.compile("/Employees/Employee/name/text()");			
			result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
			printXpathResult(result);

			// Compile the XPath expression for getting a NodeSet: Gets all age tag values from employee.xml
			System.out.println("Java XpathConstants NODESET example:::::getting all nodes age attribute");
			xPathExpr = xpath.compile("/Employees/Employee/age/text()");
			result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
			printXpathResult(result);
			
			// Compile the XPath expression for getting a NodeSet: Gets all gender tag values from employee.xml
			System.out.println("Java XpathConstants NODESET example:::::getting all nodes gender attribute");
			xPathExpr = xpath.compile("/Employees/Employee/gender/text()");
			result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
			printXpathResult(result);
			
			// Compile the XPath expression for getting a NodeSet: Gets all fulltime tag values from employee.xml
			System.out.println("Java XpathConstants NODESET example:::::getting all nodes fulltime attribute");
			xPathExpr = xpath.compile("/Employees/Employee/fulltime/text()");
			result = xPathExpr.evaluate(doc, XPathConstants.NODESET);
			printXpathResult(result);

		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
	}
	
	/**
	* Method to print result on console
	* @param result
	*/
	
	public static void printXpathResult(Object result) {
	   NodeList nodes = (NodeList) result;
	   for (int i = 0; i < nodes.getLength(); i++) {
		   System.out.println(nodes.item(i).getNodeValue());
	   }
	}
}

If we see above code sample, the method demonstrateConstants() shows how various return types are used when a xpath expression is evaluated. For this example we used employee.xml which you can refer in the section below. To get the name text value of an employee, we used XPathConstants.STRING return type. Similarly, to get the age of an employee, we used XPathConstants.NUMBER, to get fulltime boolean value, we used XPathConstants.BOOLEAN and to get the attribute values from all different nodes, we used XPathConstants.NODESET. The method printXpathResult() traverses through the nodelist to print different values on console.

3.4  Creating employee.xml

Create a new xml by Right click on Java project ->New ->Other. Search for XML.

Fig 3: Creating new XML

Select XML -> XML File and click Next.

Fig 4: New XML File

Select the recently created project and enter the XML filename i.e. employee.xml that we are using in our XPathConstantsExample.java class and click Finish. A new XML gets created in the project root directory. Refer to the screenshot below.

Fig 5: Provide XML file name

3.5 Project directory structure

The project directory structure created should be similar to the screenshot below.

Fig 6: Project directory structure

3.6 employee.xml content

Here is the content of employee.xml.

employee.xml

<?xml version="1.0" encoding="UTF-8"?>
<Employees>
  <Employee id="1">
    <age>29</age>
    <name>Pankaj</name>
    <gender>Male</gender>
    <fulltime>False</fulltime>
  </Employee>
  <Employee id="2">
    <age>35</age>
    <name>Lisa</name>
    <gender>Female</gender>
    <fulltime>False</fulltime>
  </Employee>
  <Employee id="3">
    <age>40</age>
    <name>Tom</name>
    <gender>Male</gender>
    <fulltime>True</fulltime>
  </Employee>
  <Employee id="4">
    <age>25</age>
    <name>Meghna</name>
    <gender>Female</gender>
    <fulltime>False</fulltime>
  </Employee>
</Employees>

The above xml is referred in section 3.3 above to explain various java XPathConstants. We have used all the return type values in our xml (STRING, BOOLEAN, NUMBER, NODESET) to explain our example.

3.7 Eclipse output

Run the project by Right click on project -> Run As -> Java Application.

Fig 7: Run Java Project

We can see the output as below when we run the project.

Fig 8: Eclipse Output Console

4. Conclusion

The output shows how we get XPathFactory instance and parsing the employee.xml file. We have also seen how a new XPath object has been created and a XPathExpression has been executed to demonstrate various XPathConstants.

5. Download the Eclipse Project

This was an example of using XPathConstants.

Download
You can download the full source code of this example here: XPathConstants

Neha Goel

Neha holds a Bachelors degree in Computer Science and Engineering. Currently she is working as a Sr. Programmer Analyst for a client in USA and has a total of 9+ years of Java/J2EE experience.Her expertise includes participation in all stages of SDLC. She has experience with multiple web based and enterprise based applications. She has a very impressive understanding in Object oriented architecture, analysis, design and software development using latest technologies like Java, J2EE , Restful Services, Spring, Hibernate, JDBC, JSP, Servlets, GWT, ATG etc.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button