XPath

Java XPathFactory Example

Photo of Neha GoelNeha GoelNovember 2nd, 2017Last Updated: October 31st, 2017
0 651 3 minutes read

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 extends
java.lang.Object. An XPathFactory instance can be used to create
XPath 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 useXPathFactorynewInstance() 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.

Fig 1: Creating a Java project

2.2 Creating a new XPathFactoryExample class

Create a new java class namingXPathFactoryExample.java using, Right Click on java project->New->Class.

Fig 2: Create new java 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.

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

Fig 5: XML filename

2.5 Project directory structure

Refer project directory structure below.

Fig 6: Project directory structure

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.

Fig 7: Run Java Project

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

Fig 7: Project output

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.

Download
You can download the full source code of this example here:XpathFactoryExample
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Neha GoelNeha GoelNovember 2nd, 2017Last Updated: October 31st, 2017
0 651 3 minutes read
Photo of Neha Goel

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.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.