Camel and Xpath 2.0

Camel offers you to create predicates or expressions using XPath. This can be quiet convenient when you want to route your message based on the content of an XML message or extract a value from a XML payload. XPath itself is a powerful and useful tool that allows you to make complex queries with XML. Camel uses the default XPath package that comes with Java. Unfortunately it implements the XPath 1.0 version and not the 2.0 version. This means that you miss some powerful functions.

Luckily it is easy to load the Saxon XPath factory which contain the XPath 2.0+ functionality. First add the correct dependency:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-saxon</artifactId>
    <version>2.19.0</version>
</dependency>

After this you have to add the following to your route builder class:

import net.sf.saxon.xpath.*;

…

XPathFactory fac = new XPathFactoryImpl();

from("direct:xmlSource")
        .setProperty("serviceID")
            .xpath("/service/service[lower-case(name) = 'lowercasename']/id", String.class);

Start your route and you will see a log statement saying that the Saxon XPathFactory is being used and you won’t get an exception stating that the lower-case function does not exists.