Java XPath Example Tutorial

Welcome to Java XPath Example Tutorial. XPath provides syntax to define part of an XML document. XPath Expression is a query language to select part of the XML document based on the query String. Using XPath Expressions, we can find nodes in any xml document satisfying the query string.

Java XPath

javax.xml.xpath package provides XPath support in Java. To create XPathExpression, XPath API provide factory methods.

Java XPath supported return types are defined in XPathConstants class.

  1. XPathConstants.STRING
  2. XPathConstants.NUMBER
  3. XPathConstants.BOOLEAN
  4. XPathConstants.NODE
  5. XPathConstants.NODESET

Java XPath Example

In this java XPath example tutorial, we have following sample xml file.

employees.xml

We will implement following functions in our Java XPath example program.

  1. A function that will return the Employee Name for input ID.
  2. Return list of Employees Name with age greater than the input age.
  3. Return list of Female Employees Name.

Here is the final implementation class for Java XPath example program.

XPathQueryExample.java

When we run above java XPath example program, it results in following output.

Notice that first few lines are to read the XML file as Document. Then we are reusing the Document and XPath object in all the methods. Above program shows example of NODESET and STRING as result Object.

That’s all for a quick roundup on Java XPath.

By admin

Leave a Reply

%d bloggers like this: