XPath ancestor example

In this example we will learn how to get the ancestor details of a given node using 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 the desired functionality.

Tools and technologies used in this example are Java 1.6, Maven, Intellij.(Please note you don’t need Maven to run this example. It can be run as standalone java application. You can use any IDE or even not use any if you want to.)

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. A location path can be absolute or relative. An absolute location path starts with a slash ( / ) and a relative location path does not. In both cases the location path consists of one or more steps, each separated by a slash:

An axis defines a node-set relative to the current node.

ancestorSelects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-selfSelects all ancestors (parent, grandparent, etc.) of the current node and the current node itself


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 org.w3c.dom.Document;
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.IOException;

 * Example code for XPath ancestor selection
 * @author Java Code Geeks
public class ExampleXPathAncestor {

    private static DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    private static DocumentBuilder builder = null;
    private static XPath xPath = null;
    private static Document document = null;

    public static void main(String q[]) {
        try {
            builder = builderFactory.newDocumentBuilder();
            document = builder.parse(ExampleXPathAncestor.class.getResourceAsStream("/user.xml"));
        } catch (ParserConfigurationException e) {
        } catch (SAXException e) {
        } catch (IOException e) {
        xPath =  XPathFactory.newInstance().newXPath();
        String expression = "//SecondLineOfAddress/ancestor::Address";
        try {
            NodeList nl = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {



The expression //SecondLineOfAddress/ancestor::Address will select the ancestor Address of SecondLineOfAddress.

6. Output

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


    Oxford Street

    United Kingdom

    Reagent Street

    New York

    United States

7. Download the source file

This was an example showing how to use XPath ansector.

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

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