Home » Core Java » xml » XPath » XPath starts-with example

About Mohammad Meraj Zia

Senior Java Developer

XPath starts-with example

In this example we will learn how to use starts-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 ‘starts-with’ function.

Tools and technologies used in this example are Java 1.7, Maven, Intellij.

1. Overview

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

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. We will try to extract the country names that starts with ‘United‘.


package com.javacodegeeks;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

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.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.FileNotFoundException;
import java.io.IOException;

 * Example class for describing how the XPath starts-with function works.
 * @author JavaCodeGeeks
public class ExampleXPathStartsWith {

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;

    public static void main(String q[]) {
        ExampleXPathStartsWith exampleXPathStartsWith = new ExampleXPathStartsWith();

    public void execute() {
        try {
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(this.getClass().getResourceAsStream("/user.xml"));
            XPath xPath =  XPathFactory.newInstance().newXPath();
            String expression = "//User/Address/Country[starts-with(.,'United')]";

            //read a string value
            NodeList nl = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
            for(int i=0; i < nl.getLength() ; i++) {
                Node node = nl.item(i);
        } catch (ParserConfigurationException e) {
        } catch (SAXException e) {
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        } catch (XPathExpressionException e) {

First we create a reference of DocumentBuilderFactory by calling the static newInstance method of it.

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

Then we create a DocumentBuilder object by calling newDocumentBuilder() method on the factory object.

DocumentBuilder builder = builderFactory.newDocumentBuilder();

Then we call the parse() method on this builder object by passing in the xml file that we pant to parse.

Document document = builder.parse(this.getClass().getResourceAsStream("/user.xml"));

Then we create a XPath object:

XPath xPath =  XPathFactory.newInstance().newXPath();

We will call the compile() method on this XPath object by passing in the expression and then call the evaluate() method. This will return is the list of nodes from the target xml.

NodeList nl = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

Then we will iterate these nodes to print the text content


6. Output

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

United Kingdom
United States

Process finished with exit code 0

7. Download the source file

This was an example of XPath starts-with function.

You can download the full source code of this example here: XPath-starts-with.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


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


Receive Java & Developer job alerts in your Area


Notify of

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

Inline Feedbacks
View all comments