Use of count() function in XPath
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" ?>
<AAA>
<CCC>
<BBB/>
<BBB/>
<BBB/>
</CCC>
<DDD>
<BBB/>
<BBB/>
</DDD>
<EEE>
<BCC/>
<BDD/>
</EEE>
</AAA>
|
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 =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("xmlData.xml"); |
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.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;
public class XPathCount {
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse("xmlData.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//*[count(BBB)=2]");
//Select elements which have two children BBB
System.out.println("Select elements which have two children BBB");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
System.out.println("Select elements which have 3 children");
expr = xpath.compile("//*[count(*)=3]");
//Select elements which have 3 children
result = expr.evaluate(doc, XPathConstants.NODESET);
nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeName());
}
}
}
|
To run this example follow these steps as follows:
- Create xmlData.xml file
- create and save XPathCount.java
- compile and execute XPathCount class.
Output:
Download Source Code