Java XPath – Check if node or attribute exists?

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

1. How to check if xml node exists?

To verify if node or tag exists in XML content, you can execute an xpath expression against DOM document for that XML and count the matching nodes.

  1. matching nodes > zero – XML tag / attribute exists.
  2. matching nodes <= zero – XML tag / attribute does not exist.

1.1. XML File

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

1.2. Count XML tags with XPath to check existence

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 {
		// Get DOM Node for XML
		String fileName = "employees.xml";
		Document document = getDocument(fileName);

		String xpathExpression = "";

		// Get all employee names
		xpathExpression = "/employees/employee/firstName";
		System.out.println(checkIfNodeExists(document, xpathExpression));	//true
		
		// Get all employee ids
		xpathExpression = "/employees/employee/@id";
		System.out.println(checkIfNodeExists(document, xpathExpression));	//true
		
		// Get all employee age
		xpathExpression = "/employees/employee/@age";
		System.out.println(checkIfNodeExists(document, xpathExpression));	//false

		// Get all department names
		xpathExpression = "/employees/employee/department/name";
		System.out.println(checkIfNodeExists(document, xpathExpression));	//true
		
		// Get department locations
		xpathExpression = "/employees/employee/department/location";
		System.out.println(checkIfNodeExists(document, xpathExpression));	//false
	}

	private static boolean checkIfNodeExists(Document document, String xpathExpression) throws Exception 
	{
		boolean matches = false;
		
		// Create XPathFactory object
		XPathFactory xpathFactory = XPathFactory.newInstance();

		// Create XPath object
		XPath xpath = xpathFactory.newXPath();

		try {
			// Create XPathExpression object
			XPathExpression expr = xpath.compile(xpathExpression);

			// Evaluate expression result on XML document
			NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
			
			if(nodes != null  && nodes.getLength() > 0) {
				matches = true;
			}

		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		return matches;
	}
	
	private static Document getDocument(String fileName) throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(true);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(fileName);
		return doc;
	}	
}

Program Output:

true
true
false
true
false

Read More: Xpath Examples

Happy Learning !!

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

2 thoughts on “Java XPath – Check if node or attribute exists?”

  1. This is useless, because most xml is namespace defined. This is useless unless you provide xpath a way to determine the namespace

    Reply

Leave a Comment

HowToDoInJava

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