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

<my-example-data>
<id>1234</id>
<fname>First Name</fname>
<mname>Middle Name</mname>
<lname>Last Name</lname>
<jobTitle>Job Title</jobTitle>
</my-example-data>

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="http://www.milyn.org/xsd/smooks-1.1.xsd"
xmlns:jb="http://www.milyn.org/xsd/smooks/javabean-1.1.xsd">
<jb:bindings beanId="inquiryMap" class="java.util.HashMap" createOnElement="$document">
<jb:value data="inquiry-email-data/*"/>
</jb:bindings>
</smooks-resource-list>

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 http://www.smooks.org/news/eclipseeditorforsmooksinjbosstools.

2 comments:

guptha said...

hi
can you provide source code for this smooks xml2java transformation

Kurt Stam said...

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