XPath count example

In the previous example, we studied how to use the XPath Concat method. In this example, we will see how to use the count method in XPath.

The XPath count() method is used to count the number of nodes matching a given XpathExpression.

Let’s look at a few examples to understand how the count method works. Consider the XML file below for our examples:

<?xml version="1.0" encoding="UTF-8"?>

	<cricketer type="righty">
		<name>MS Dhoni</name>
	<cricketer type="lefty">
		<name>Shikhar Dhawan</name>
	<cricketer type="righty">
		<name>Virat Kohli</name>
	<cricketer type="righty">
	<cricketer type="lefty">
		<name>Zaheer Khan</name>

Now, let’s count the number of cricketers:


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;

public class XpathCountFunctionDemo
	public static void main(String[] args) throws Exception
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		Document doc = documentBuilder.parse("src/cricketTeam_info.xml");

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

		//XPath count() example
		XPathExpression expr = xpath.compile("count(//cricketers/cricketer)");
		Number result = (Number) expr.evaluate(doc, XPathConstants.NUMBER);
		System.out.println("Total number of Cricketers in the squad is "+result);


Total number of Cricketers in the squad is 5.0

We tried to count the number of <cricketer> tags under the <cricketers> tag. To achieve this, we simply pass the qualified tag path to the count method. The count method is quite flexible. For example, if we want to find the number of Bowlers (role = Bowler) in the team, we do it in the following manner:

//XPath count() example
XPathExpression expr = xpath.compile("count(//cricketers/cricketer[role='Bowler'])");
Number result = (Number) expr.evaluate(doc, XPathConstants.NUMBER);
System.out.println("The 'Bowlers' count in the squad is "+result);


The 'Bowlers' count in the squad is 2.0

Since there are two nodes with tag role=Bowler, we get count as 2.

Here, we studied how we can use the count() method in XPath

You can download the source code of this example here: XpathCountFunctionDemo.zip

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button