Last Updated:

XPath in Java | Searching XML and fetching data

In this article, we will look at an example of working with XPath in Java, namely, we will learn how to find the information we need using XPath expressions and make a selection from an XML document under various conditions.

XPath at a glance

XPath provides a special syntax for finding and retrieving data in an XML document. Using XPath expressions, we can fetch by condition, find nodes or the exact value from any part of the XML document.

XPath is part of the Java SE platform and is packaged, so no additional dependencies need to be plugged in— everything works right out of the box.javax.xml.xpath

To create an expression to be selected by a condition, use the class , which is created by using factory methods and a call to the . The result of the sample should be represented by one of 5 possible types:XPathExpressionXPathFactory.newInstance()xpathFactory.newXPath()

  • XPathConstants.STRING
  • XPathConstants.NUMBER
  • XPathConstants.BOOLEAN
  • XPathConstants.NODE
  • XPathConstants.NODESET

More details below in the example.

Example of working with XPath in Java

We are faced with the task of obtaining information from the XML file of developers according to the following criteria:

  1. Find out the names of developers whose age is less than specified in the condition.
  2. Get the names of all the middles.
  3. Get the name by a well-known id.

We have an XML document with the following content:

How do I search with XPath?

Consider one of the expressions that we will use in our program:XPathExpression

Get the names of all the middles:

In this case, a string with search criteria (an expression) is passed to the input method, the results of which create a new object.compile()XPathExpression

In the expression itself, we specify what we want to look for in the Developer nodes that are in the root Developers. In each of these Developer nodes, we want to go to the position tag and see if its value is 'Middle' — if true, then go to the name tag of the current Developer node and get the value of this tag using the text() method.

Similarly, we work with other conditions, only instead of the condition [position='Middle'] we set the appropriate criteria:

Age less than set in :age

Name by known :id

You can find the id, for example, by name:

Note that the id attribute uses the character .@

Now let's write a class that implements the tasks described above:

Now let's run our program and see the output to the console:

As you can see, all the results of the sample are the same as the data in the source XML file.