The primary goals of this example are to introduce you to the following:
- Transforming from csv file to xml.
- The Smooks configuration file.
- Executing the Smooks Transformation.
SVN - Download - Other Tutorials
Other Relevant Info:
- xslt-basic tutorial.
- XSLT Configuration Javadocs.
To Build: "mvn clean install"
To Run: "mvn exec:java"
Transforming from csv file to xml
This is a very simple example that illustrates how Smooks to configure in a non-XML stream parser (CSV) into Smooks.
So here's the source csv file that is to be transformed:
Tom,Fennelly,Male,4,Ireland Mike,Fennelly,Male,2,Ireland
And this is the expected result of our transformation:
<csv-set> <csv-record> <firstname>Tom</firstname> <lastname>Fennelly</lastname> <gender>Male</gender> <age>4</age> <country>Ireland</country> </csv-record> <csv-record> <firstname>Mike</firstname> <lastname>Fennelly</lastname> <gender>Male</gender> <age>2</age> <country>Ireland</country> </csv-record> </csv-set>
The Smooks Configuration
In order to apply this transformer to a message fragment, a Smooks Configurationneeds to be created. This configuration will target the transformer at a particular message fragment. For more information on configuring XSLT resources, see XslContentDeliveryUnitCreator.
Here's the configuration ("smooks-config.xml"):
<?xml version="1.0"?> <smooks-resource-list xmlns="http://www.milyn.org/xsd/smooks-1.0.xsd"> <!--Configure the CSVParser to parse the message into a stream of SAX events. --> <resource-config selector="org.xml.sax.driver"> <resource>org.milyn.csv.CSVParser</resource> <param name="fields" type="string-list">firstname,lastname,gender,age,country</param> </resource-config> </smooks-resource-list>
Executing The Transformation
Again, it's exactly the same as with the java-basic tutorial:
Smooks smooks = new Smooks("smooks-config.xml");
StandaloneExecutionContext executionContext = smooks.createExecutionContext();
smooks.filter(new StreamSource(new InputStreamReader(new ByteArrayInputStream(messageIn), "UTF-8")), new StreamResult(writer), executionContext);
Of course, you'd typically cache the Smooks instance.
See the example/Main.java in the example source.