A shortcut for PMD XPath rules

02 Jul 2007

The normal path for experimenting with a PMD XPath rule is to run the rule designer, paste in some Java source code, paste in the XPath expression, and see what it returns. But if you just want to try out an XPath expression and see what it returns in a particular file, there's some code in Subversion to do that now.

Here's how to use it. You need a Java source file to run it on:

package foo;
public class Test {
  private int x;
  private int y;
}

Then you can run the XPathTest class and feed it the XPath expression and the filename:

$ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration" -filename ~/tmp/Test.java 
Match at line 3 column 11; package name 'foo'; variable name 'x'
Match at line 4 column 11; package name 'foo'; variable name 'y'

This accepts any valid XPath expression, so you can limit the results to fields named 'x' by specifying an attribute predicate:

$ java net.sourceforge.pmd.util.XPathTest -xpath "//FieldDeclaration[@VariableName='x']" -filename ~/tmp/Test.java 
Match at line 3 column 11; package name 'foo'; variable name 'x'

You can download this feature in this updated pmd-4.0rc1.jar file. Enjoy! And if you're using PMD, get the PMD book!