In this example, we will see what is javaXPathFactory and its usage with example. Before we start with this article, it is expected that we have a basic understanding of XML. XML stands for eXtensible Markup Language, which is designed to store and transport data. It is both human and machine readable.
1. Introduction
XPathFactory is an abstract class in java that extendsjava.lang.Object. An XPathFactory instance can be used to createXPath objects. 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.
Java classes from java.xml.xpath package e.g. XPath, XPathFactory and XPathExpression are used to create and evaluateXpath in Java.
In this example, we will see how to useXPathFactory, newInstance() method to get aXPath instance and traverse the XML.
2. Demonstration
Let us write a java program to demonstrate how to get a newXPathFactory instance, createXPath expression and how to executeXPath expression to retrieve text value, numeric and boolean value.
2.1 Creating a java project
Create a new java project in eclipse using File -> New ->Java Project. Enter the project name “XPathFactoryExample” and a new java project should get created. Refer screenshot below.

2.2 Creating a new XPathFactoryExample class
Create a new java class namingXPathFactoryExample.java using, Right Click on java project->New->Class.
2.3 XPathFactoryExample.java
After creating a new class, Refer the code below for XPathFactoryExample.java.
XPathFactoryExample.java
package com.xpath.example;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;//XPathFactoryExample -Java examplepublic class XPathFactoryExample { 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 xPath Expr = 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);}/** * Method to print result on console * @param result */ public void printXpathResult(Object result) { NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } }//Main class to run the example. public static void main(String[] args) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException { XPathFactoryExample xPathExample = new XPathFactoryExample(); xPathExample.xPathProcessor(); }} 2.4 Creating smartphone.xml
Create a new xml by Right click on Java project ->New ->Other. Search for XML.
Select XML -> XML File and click Next.
Select the recently created project and enter the XML filename i.e. smartphone.xml that we are using in ourXPathFactory.java class and click Finish. A new XML gets created in the project root directory. Refer screenshot below.
2.5 Project directory structure
Refer project directory structure below.

2.6 smartphone.xml content
Here is the content of smartphone.xml.
smartphone.xml
<?xml version="1.0" encoding="UTF-8"?><smartphones> <smartphone> <brand> <text> Samsung </text> </brand> <model> Note3 </model> </smartphone> <smartphone> <brand> <text> Apple </text> </brand> <model> IPhone8 </model> </smartphone></smartphones>
2.7 Eclipse output
Run the project by Right click on project -> Run As -> Java Application.
We can see the output as below when we run the project.
3. Conclusion
The output shows, how we getXPathFactory instance, and parse thesmartphone.xml file. We have also seen how a newXPath object has been created and a XPathExpression has been executed to retrieve text value, numeric value and boolean value.
4. Download the Eclipse Project
This was an example of using XPathFactory.
You can download the full source code of this example here:XpathFactoryExample

Thank you!
We will contact you soon.









