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:

Lokesh
1
2

2. XML file

The input xml file is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees>
    <employee id="1">
        <firstName>Lokesh</firstName>
        <lastName>Gupta</lastName>
        <department>
            <id>101</id>
            <name>IT</name>
        </department>
    </employee>
    <employee id="2">
        <firstName>Brian</firstName>
        <lastName>Schultz</lastName>
        <department>
            <id>102</id>
            <name>HR</name>
        </department>
    </employee>
</employees>

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+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.