XPath – how to create a custom rule

By , last updated July 11, 2016

After I began to use PMD and tried to write my first custom XPath rules, I realised that there aren’t very much information about it. So I needed to figure out almost everything by myself. Here I’ll try to explain what I’ve figured out.

I use Eclipse 3.5 to run the rules, by the way.

1. Create a new ruleset file as described here.
2. Check if you need a special encoding for the language you are going to use. I was using a norwegian language, so I needed to add encoding=”ISO-8859-1″ to xml header:

<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>

3.Begin writing a custom rule:

<rule name="MoreThanOneLoggUtil"
      message="You are using more that one LoggUtil instance. Only one is legal."
   You are using more that one LoggUtil instance. Only one is legal.
   <property name="xpath">
          ... (some XPath code here) ...
public class Foo
     private LoggUtil log = new LoggUtil(Foo.class);
     private LoggUtil log2 = new LoggUtil(Foo.class);

Senior Software Engineer developing all kinds of stuff.


  1. Robert W. February 20, 2015 Leave a Reply

    Great howto! Thank you (and c&p 😉 )

    Btw: You are missing an equal sign in ‘name”MoreThanOneLoggUtil”‘.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>