Home | Forums

Extracting coverage data programmatically

Using XPath with Clover's XML reports

Clover's XML reports provide detailed coverage data in a format that is easy to access programmatically using XPath. XML coverage reports can be generated by the <clover-historypoint> Ant tasks, via the Swing Viewer. The following example XPath expressions show how to extract data from a Clover XML coverage report:

/coverage/project/metrics[@statements]

Extracts the total number of statements in the project.

/coverage/project/metrics[@coveredstatements]

Extracts the total number of uncovered statements in the project.

/coverage/project/package[name='com.foo.bar']/metrics[@statements]

Extracts the total number of statements in the package com.foo.bar

/coverage/project/package[name='com.foo.bar']/metrics[@coveredstatements]

Extracts the total number of covered statements in the package com.foo.bar

An XPath implementation is shipped with the JDK1.5 distribution. Third party implementations that work with JDK1.4 and below include Jaxen, Dom4j, and JXP

The following code example (using the JDK1.5 implementation of XPath) demonstrates simple extraction of coverage data from a Clover XML report:

 import javax.xml.xpath.*;
 ...
 XPath xpath = XPathFactory.newInstance().newXPath();
 String stmtExpr = "/coverage/project/metrics[@statements]";
 String coveredStmtExpr = "/coverage/project/metrics[@coveredstatements]";
 InputSource inputSource = new InputSource("coverage.xml");
 Double projectStatements = (Double) xpath.evaluate(expression, inputSource,
                                                    XPathConstants.NUMBER);
 Double projectCoveredStatements = (Double) xpath.evaluate(expression, inputSource,
                                                           XPathConstants.NUMBER);
 ...