Java xpath example – Evaluate xpath on xml file

Java xpath example to read an XML file and parse to DOM object, then evaluate xpath on org.w3c.dom.Document object and get results in form of String or NodeList.

1. Java evaluate xpath on xml file

  1. Create Document DOM object javax.xml.parsers.DocumentBuilder object.
  2. Create XPath from XPathFactory.
  3. Use xpath.evaluate('expression', dom, resultType) to get result HTML.
package com.howtodoinjava.demo;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class XPathExample 
	public static void main(String[] args) throws Exception 

		String xmlFile = "employees.xml";
		//Get DOM
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document xml = db.parse(xmlFile);

        //Get XPath 
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        //Get first match
        String name = (String) xpath.evaluate("/employees/employee/firstName", xml, XPathConstants.STRING);
        System.out.println(name);	//Lokesh
        //Get all matches
        NodeList nodes = (NodeList) xpath.evaluate("/employees/employee/@id", xml, XPathConstants.NODESET);
        for (int i = 0; i < nodes.getLength(); i++) {
        	System.out.println(nodes.item(i).getNodeValue());	//1 2

Program output:


2. XML file

The input xml file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <employee id="1">
    <employee id="2">

Happy Learning !!

Read More:

Java xpath example from string
Java xpath tutorial
How to get attribute value in xml using xpath in java

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.