Use Xalan’s extension functions natively in jOOX

jOOX - a jQuery port to Java jOOX aims at increased ease of use when dealing with Java’s rather complex XML API’s. One example of such a complex API is Xalan, which has a lot of nice functionality, such as its extension namespaces. When you use Xalan, you may have heard of those extensions as documented here:

These extensions can typically be used in XSLT. An example is the math:max function:

<!-- Source -->

<!-- Stylesheet -->
<xsl:template match="values">
      <xsl:text>Maximum: </xsl:text>
      <xsl:value-of select="math:max(value)" />

<!-- Result -->
<result>Maximum: 11</result>

But in fact, math:max can be used in any type of XPath expression, also the ones that are directly created in Java. Here’s how you can do this:

Document document = // ... this is the DOM document

// Create an XPath object
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();

// Initialise Xalan extensions on the XPath object
  new org.apache.xalan.extensions.ExtensionNamespaceContext());
  new org.apache.xalan.extensions.XPathFunctionResolverImpl());

// Evaluate an expression using an extension function
XPathExpression expression = xpath.compile(
  "//value[number(.) = math:max(//value)]");
NodeList result = (NodeList) expression.evaluate(
  document, XPathConstants.NODESET);

// Iterate over results
for (int i = 0; i < result.getLength(); i++) {

jOOX is much more convenient

The above is pretty verbose. With jOOX, you can do exactly the same, but with a lot less code:

Document document = // ... this is the DOM document

// jOOX's xpath method already supports Xalan extensions
for (Match value : $(document).xpath(
    "//value[number(.) = math:max(//value)]").each()) {

Tags: , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 3,344 other followers

%d bloggers like this: