jOOX and XSLT. An XML love story, continued

jOOX - a jQuery port to Java The somewhat functional way of thinking involved with jOOX’s XML manipulation cries for an additional API enhancement simply supporting XSLT. XSL transformation has become quite a standard way of transforming large amounts of XML into other structures, where normal DOM manipulation (or jOOX manipulation) becomes too tedious. Let’s have a look at how things are done in standard Java

Example input:

  <book id="1"/>
  <book id="2"/>

Example XSL:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"

    <!-- Match all books and increment their IDs -->
    <xsl:template match="book">
        <book id="{@id + 1}">

    <!-- Identity-transform all the other elements and attributes -->
    <xsl:template match="@*|*">
            <xsl:apply-templates select="*|@*"/>

Verboseness of XSL transformation in Java

The standard way of doing XSL transformation in Java is pretty verbose – as just about anything XML-related in standard Java. See an example of how to apply the above transformation:

Source source = new StreamSource(new File("increment.xsl"));
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(source);
DOMResult result = new DOMResult();
transformer.transform(new DOMSource(document), result);

Node output = result.getNode();

Drastically decrease verbosity with jOOX

With jOOX, you can write exactly the same in much less code:

Apply transformation:
// Applies transformation to the document element:

// Applies transformation to every book element:

The result in both cases is:

  <book id="2"/>
  <book id="3"/>

CSS selectors in Java

CSS selectors are a nice and intuitive alternative to XPath for DOM navigation. While XPath is more complete and has more functionality, CSS selectors were tailored for HTML DOM, where the document content is usually less structured than in XML.

Here are some examples of CSS selector and equivalent XPath expressions:

CSS:   document > library > books > book
XPath: //document/library/books/book

CSS:   document book
XPath: //document//book

CSS:   document book#id3
XPath: //document//book[@id='3']

CSS:   document book[title='CSS for dummies']
XPath: //document//book[@title='CSS for dummies']


This becomes more interesting when implementing pseudo-selectors in XPath:

CSS:   book:first-child
XPath: //book[not(preceding-sibling::*)]

CSS:   book:empty
XPath: //book[not(*|@*|node())]


A very nice library that allows for parsing selector expressions according to the w3c specification is this “css-selectors” by Christer Sandberg:

The next version of jOOX will include css-selector’s parser for simpler DOM navigation. The following two expressions will hold the same result:

Match match1 = $(document).find("book:empty");
Match match2 = $(document).xpath("//book[not(*|@*|node())]");