In the previous section of XPath in Java tutorial we have studied about how to run XPath query in java and in this section we are going to see how we can implement count() function in the XPath query.
First of all we have created an XML file xmlData.xml. This xml file contains various nodes and we have used count() function in our XPathCount class to count different nodes with their specific values.
Here is the full example code of xmlData.xml as follows:
xmlData.xml
<?xml version="1.0" ?>
|
Now we have declared a class XPathCount and in this class we are parsing the XML file with JAXP. First of all we need to load the document into DOM Document object. We have put that xmlData.xml file in that current working directory.
DocumentBuilderFactory domFactory = |
Above lines of code parses "xmlData.xml" file and creates a Document object. Next we have created XPath object with the use of XPathFactory.
XPath xpath = XPathFactory.newInstance().newXPath(); |
Expression "//*[count(BBB)=2]" will select elements which have two children BBB and "//*[count(*)=3]" will select elements which have 3 children. Here is the full example code of XPathCount.java as follows:
XPathCount.java
import org.w3c.dom.*;
|
To run this example follow these steps as follows:

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Use of count() function in XPath View All Comments
Post your Comment