HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java XML / Java XPath – Check if node or attribute exists?

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

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. kevin2

    January 17, 2020

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

    • Lokesh Gupta

      January 17, 2020

      Yes, you should know the namespace and xml structure beforehand.

Comments are closed on this article!

Search Tutorials

Java XML Tutorial

  • Java – Read XML DOM Parser
  • Java – Read XML SAX Parser
  • Java – Read XML JDOM2 Parser
  • Java – Read XML StAX Parser
  • Java – DOM vs SAX Parser
  • Java – Convert XML to Properties
  • Java – Convert Properties to XML
  • Java – Convert String to XML
  • Java – Convert XML to String
  • Java – XPath Tutorial
  • Java – Evaluate XPath on DOM
  • Java – Evaluate XPath on String
  • Java – XPath Examples
  • Java – XPath NamespaceContext
  • Java – Get Attribute using XPath
  • Java – XPath Attribute Examples
  • Java – Check if XML tag exists?

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)