Java XPath – Check if Node or Attribute Exists?

Java xpath check if node exists or check if attribute exists in Java with example by execute an xpath expression to count the matching nodes.

xml

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
//employees/employee/@id 

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
count(//employees/employee/@id)

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

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();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse("employees.xml");

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

    //1
    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");
    }

    //2
    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

Weekly Newsletter

Stay Up-to-Date with Our Weekly Updates. Right into Your Inbox.

Comments

Subscribe
Notify of
2 Comments
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.