XPath ends-with example

In this example we will learn how to use the ends-with function of XPath. We will start with the introduction of XPath – what it is and how to use it, then we will see the working model of ends-with function.
Tools and technologies used in this example are Java 1.7, Maven, Intellij, Saxon.

1. Overview

An XPath expression specifies a pattern that selects a set of XML nodes. XSLT templates then use those patterns when applying transformations. The nodes in an XPath expression refer to more than just elements. They also refer to text and attributes, among other things. In fact, the XPath specification defines an abstract document model that defines seven kinds of nodes:

  • Root
  • Element
  • Text
  • Attribute
  • Comment
  • Processing instruction
  • Namespace

XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value. XPath is a W3C-defined language and an official W3C recommendation; the W3C hosts the XML Path Language (XPath) Version 1.0 specification.

2. XPath Expressions

An XPath expression is composed of a location path and one or more optional predicates. Expressions may also include XPath variables.

The following is an example of a simple XPath expression:


This example would select the <City> element in an XML document

ends-with(string1,string2), returns true if string1 ends with string2, otherwise it returns false
Example: ends-with(‘JAVA’,’A’)
Result: true

3. Project Structure

Below is the project structure used in this example

Figure 1. Project Structure
Figure 1. Project Structure

4. XLM file

Below is the xml file representing Users. Each user has got a unique UserId, name, address, sex, Date Of Birth and email.


<?xml version="1.0" encoding="UTF-8"?>
            <FirstLineOfAddress>Oxford Street</FirstLineOfAddress>
            <Country>United Kingdom</Country>
            <FirstLineOfAddress>Reagent Street</FirstLineOfAddress>
            <City>New York</City>
            <Country>United States</Country>
            <FirstLineOfAddress>Panama Street</FirstLineOfAddress>

5. Java file

Below is the java file which will use XPath to extract information from the User.xml.


package com.javacodegeeks;

import net.sf.saxon.om.NamespaceConstant;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

 * Example to use XPath 'ends-with' function.
 * @author JavaCodeGeeks
public class ExampleXPathEndsWith {

    public static final String XPATH_EXPRESSION = "//User/Address/Country[ends-with(text(), \"Kingdom\")]";
    private DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    private DocumentBuilder builder = null;

    public static void main(String q[]) {
        ExampleXPathEndsWith exampleXPathEndsWith = new ExampleXPathEndsWith();

    private void execute() {
            System.setProperty("javax.xml.xpath.XPathFactory:"+ NamespaceConstant.OBJECT_MODEL_SAXON, "net.sf.saxon.xpath.XPathFactoryImpl");
            XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(this.getClass().getResourceAsStream("/user.xml"));

            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(XPATH_EXPRESSION);
            Object result = expr.evaluate(document, XPathConstants.NODESET);
            NodeList nodes = (NodeList) result;
        catch(Exception e){

6. pom.xml

Below is the pom.xml which has two dependencies for ‘saxon’.


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">




7. Saxon

ends-with function is available in XPath 2.0. For this we use Saxon.

This API is based on the class net.sf.saxon.xpath.XPathEvaluator. This class provides a few simple configuration interfaces to set the source document, the static context, and the context node, plus a number of methods for evaluating XPath expressions.

There are two methods for direct evaluation of XPath expressions, evaluate() which returns a List containing the result of the expression (which in general is a sequence), and evaluateSingle() which returns the first item in the result (this is appropriate where it is known that the result will be single-valued). The results are returned as NodeInfo objects in the case of nodes, or as objects of the most appropriate Java class in the case of atomic values: for example, Boolean, Double, or String in the case of the traditional XPath 1.0 data types.

8. Output

Run the ExampleXPathEndsWith.java file. Below is the generated output.

United Kingdom

9. Download the source file

This was an example of XPath 'ends-with' function.

You can download the full source code of this example here : XPath-Ends-With

Mohammad Meraj Zia

Senior Java Developer
Notify of

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

Inline Feedbacks
View all comments
Back to top button