Java XPath – Check if Node or Attribute Exists?

Java example to check if a node exists in given XML content or check if an attribute exists in XML using XPath.

1. How to check if an XML node or attribute exists?

To verify if a node or tag exists in an XML document, we can use one of two approaches:

1. Select the nodes using XPath expression and count the matches.

  • matching_nodes > zero‘ means XML tag/attribute exists.
  • matching_nodes <= zero‘ means XML tag/attribute does not exist.
#Expression for finding all employee ids where id is an attribute

2. Use count() function is the expression to directly access the count of matching nodes. If count is greater than zero, then the node exists, else not.

#Directly count all the ids

2. Demo

2.1. XML File

For demo purposes, we are using the following XML file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

  <employee id="1">

  <employee id="2">


2.2. XPath Evaluation

The following code uses both of the above-discussed techniques to find if a node or attribute exists. To understand the code in-depth, read the XPath tutorial.

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

public class CheckIfNodeExists {

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

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("employees.xml");

    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();

    XPathExpression expr = xpath.compile("//employees/employee/@id");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    if(nodes.getLength() > 0) {
      System.out.println("Attribute or Node Exists");
    } else {
      System.out.println("Attribute or Node Does Not Exist");

    expr = xpath.compile("count(//employees/employee/@id)");
    result = expr.evaluate(doc, XPathConstants.NUMBER);
    Double count = (Double) result;
    if(count > 0) {
      System.out.println("Attribute or Node Exists");
    } else {
      System.out.println("Attribute or Node Does Not Exist");


Program Output:

Attribute or Node Exists
Attribute or Node Exists

Happy Learning !!

Sourcecode in Github


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.