XPath

Java XPathFactory Example

In this example, we will see what is java XPathFactory 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 evaluate Xpath in Java.

In this example, we will see how to use XPathFactorynewInstance() method to get a XPath instance and traverse the XML.

2. Demonstration

Let us write a java program to demonstrate how to get a new XPathFactory instance, create XPath expression and how to execute XPath 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 naming XPathFactoryExample.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 example
public 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 our XPathFactory.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 get XPathFactory instance, and parse the smartphone.xml file. We have also seen how a new XPath 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

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
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button