Skip to end of metadata
Go to start of metadata

This example demonstrates how Groovy can be used to perform Fragment based Transforms through Smooks.

SVN - Download - Other Tutorials

To Build: "mvn clean install"
To Run: "mvn exec:java"

See Mixing DOM and SAX Models with Smooks


In this example, we want to modify the "supplies" category in a Shopping list message, adding 2 to the quantity, where the item is "Pens".

The Input Message

The input message is a Shopping list:

    <category type="groceries">
    <category type="supplies">
        <item quantity="4">Pens</item>
    <category type="present">
        <item when="Aug 10">Kathryn's Birthday</item>

The Smooks Configuration

To do this, we write a simple little Groovy script and target it at the <category> elements in the message. The script simply iterates over the <item> elements in the category and increments the quantity by 2, where the category type is "supplies" and the item is "Pens":

<?xml version="1.0"?>
<smooks-resource-list xmlns="" xmlns:g="">

        <param name="stream.filter.type">SAX</param>

    <g:groovy executeOnElement="category">
            use(DOMCategory) {

                // Modify "supplies": we need an extra 2 pens...
                if (category.'@type' == 'supplies') {
                    category.item.each { item ->
                        if (item.text() == 'Pens') {
                            item['@quantity'] = item.'@quantity'.toInteger() + 2;

            // When using the SAX filter, we need to explicitly write the fragment 
            // to the result stream...


The result of running this transform on the specified input message will simply modify the quantity value on the "Pens" item from 4 to 6.

Executing Smooks

protected static String runSmooksTransform(Reader messageIn) throws IOException, SAXException, SmooksException {
    Smooks smooks = new Smooks("smooks-config.xml");
    StringResult result = new StringResult();

    smooks.filter(new StreamSource(messageIn), result);

    return result.toString();

Of course, you'd typically cache the Smooks instance, and if the Result was potentially a huge message, then you'd more likely stream the result to a file (for example).

See the example/ in the example source.

  • No labels