XPath count example
In theprevious example, we studied how to use the XPathConcat method. In this example, we will see how to use thecount method in XPath.
TheXPath count() method is used to count the number of nodes matching a givenXpathExpression.
Let’s look at a few examples to understand how thecount method works. Consider theXML file below for our examples:
cricketTeam_info.xml:
<?xml version="1.0" encoding="UTF-8"?><cricketers><cricketer type="righty"><name>MS Dhoni</name><role>Captain</role><position>Wicket-Keeper</position></cricketer><cricketer type="lefty"><name>Shikhar Dhawan</name><role>Batsman</role><position>Point</position></cricketer><cricketer type="righty"><name>Virat Kohli</name><role>Batsman</role><position>cover</position></cricketer><cricketer type="righty"><name>Shami</name><role>Bowler</role><position>SquareLeg</position></cricketer><cricketer type="lefty"><name>Zaheer Khan</name><role>Bowler</role><position>FineLeg</position></cricketer></cricketers>
Now, let’s count the number of cricketers:
XpathCountFunctionDemo.java:
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();documentBuilderFactory.setNamespaceAware(true);DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();Document doc = documentBuilder.parse("src/cricketTeam_info.xml");XPathFactory xpathFactory = XPathFactory.newInstance();XPath xpath = xpathFactory.newXPath();//XPath count() exampleXPathExpression 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);}}Output:
Total number of Cricketers in the squad is 5.0
We tried tocount the number of<cricketer> tags under the<cricketers> tag. To achieve this, we simply pass the qualified tag path to thecount method. Thecount method is quite flexible. For example, if we want to find the number ofBowlers (role = Bowler) in the team, we do it in the following manner:
//XPath count() exampleXPathExpression 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);Output:
The 'Bowlers' count in the squad is 2.0
Since there are two nodes with tagrole=Bowler, we get count as 2.
Here, we studied how we can use thecount() method inXPath
You can download the source code of this example here:XpathCountFunctionDemo.zip

Thank you!
We will contact you soon.



