Java XPath – Find XML Nodes by Attribute Value

This Java tutorial demonstrates how to get matching nodes for an attribute value in an XML document using XPath.

1. XPath Expressions

1.1. Input XML File

First look at the XML file which we will read and then fetch information from it, using xpath queries.

<?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. XPath Expressions

Now see a few examples of how to build an xpath expression.

DescriptionXPath
Get all employee ids/employees/employee/@id
Get all employees with id equals to 1/employees/employee[@id = 1]
Get all employees with id greater than 1/employees/employee[@id > 1]
Get all employees with id contains 1/employees/employee[contains(@id,'1')]
Get department of all employees with id contains 1/employees/employee[contains(@id,'1')]/department
Get first name whose id contains ‘1’ in any child nodesdescendant-or-self::*[contains(@id,'1')]/firstName/text()

2. Using XPath to Find Nodes for Specified Attribute Value

Let’s look at the code which has been used to evaluate the above xpath expressions to select nodes having certain attribute values.

2.1. XPath Evaluation

To evaluate xpath in java, we need to follow these steps:

  • Read XML file into org.w3c.dom.Document.
  • Create XPathFactory with its newInstance() static method.
  • Get XPath instance from XPathFactory. This object provides access to the xpath evaluation environment and expressions.
  • Create an xpath expression string. Convert xpath string to XPathExpression object using xpath.compile() method.
  • Evaluate xpath against the document instance created in the first step. It will return a list of DOM nodes from the document.
  • Iterate nodes and get the test values using getNodeValue() method.

The following code creates a DOM Node for an XML file.

An XPath expression is not thread-safe. It is the application’s responsibility to make sure that one XPathExpression object is not used from more than one thread at any given time, and while the evaluate method is invoked, applications may not recursively call the evaluate method.

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

Next, the following function takes the DOM model and XPath expression, and returns all values obtained from evaluating the expression.

private static List<String> evaluateXPath(Document document, String xpathExpression) {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    List<String> values = new ArrayList<>();

    try {

      XPathExpression expr = xpath.compile(xpathExpression);
      NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); i++) {

        
       //Customize the code to fetch the value based on the node type and hierarchy 
        values.add(nodes.item(i).getNodeValue());
      }
    } catch (XPathExpressionException e) {
      e.printStackTrace();
    }
    return values;
  }

2.2. Example

Now, we can test the expressions we discussed in the first section. Find id attribute value for all employees.

String xpathExpression = "/employees/employee/@id";
evaluateXPath(document, xpathExpression);

Program Output:

[1, 2]

Drop me your questions related to how to find xml element with attribute value using xpath.

Happy Learning !!

Comments

Subscribe
Notify of
guest
5 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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode