Wednesday, March 25, 2009

Smooks XML2Java Transformation

Previously I wrote about using Smooks for XML2XML transformations. Today I worked on an XML2Java transformation. It so happens that my incoming XML is completely flat, and looks like

<fname>First Name</fname>
<mname>Middle Name</mname>
<lname>Last Name</lname>
<jobTitle>Job Title</jobTitle>

Which lends itself really well to be stuffed into a Map, with the key being the name of the element. This is where a really handy Smooks trick comes in handy

<?xml version="1.0"?>
<smooks-resource-list xmlns=""
<jb:bindings beanId="inquiryMap" class="java.util.HashMap" createOnElement="$document">
<jb:value data="inquiry-email-data/*"/>

Now when running the following code:

Smooks smooks = new Smooks("smooks-config.xml");
JavaResult javaResult = new JavaResult();
smooks.filter(new StreamSource(new StringReader(xml)), javaResult);
Map results = (Map<String,String>) javaResult.getBean("inquiryMap");
System.out.println("result=" + results);

It prints out:

results={lname=Last Name, mname=Middle Name, fname=First Name, id=1234, jobTitle=Job Title}

The Smooks User Guide talks about something similar when your XML uses property elements.

By the way if you like mapping out your transformation graphically you should check out the new Smooks Graphical Editor.

The Eclipse plugin can be downloaded from


guptha said...

can you provide source code for this smooks xml2java transformation

Kurt Stam said...

I did.. it is the third fragment. --Kurt