This solution uses two jars and a very small part of the Smooks api. Just include milyn-smooks-core-1.2.1.jar and milyn-commons-1.2.1.jar in your project and test drive this code:
import java.io.StringWriter;
import java.util.Properties;
import javax.xml.transform.stream.StreamResult;
import org.milyn.GenericReaderConfigurator;
import org.milyn.Smooks;
import org.milyn.container.ExecutionContext;
import org.milyn.payload.JavaSource;
public class Serializer {
private static Smooks smooks;
static {
try {
smooks = new Smooks();
// This configuration uses a sax processor to create the serialize
// xml from the java object. It isn't strictly necessary, but it is
// not a bad idea.
Properties parameters = new Properties();
parameters.put("stream.filter.type", "SAX");
GenericReaderConfigurator readerConfigurator = new GenericReaderConfigurator();
readerConfigurator.setParameters(parameters);
smooks.setReaderConfig(readerConfigurator);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String serialize(Object obj) {
ExecutionContext executionContext = smooks.createExecutionContext();
StringWriter writer = new StringWriter();
smooks.filterSource(executionContext, new JavaSource(obj),
new StreamResult(writer));
return writer.toString();
}
}
The XML that gets produced is extremely clean and ready for XSLT data extraction.
Incidentally, the Smooks instance is thread safe and may be cached. The ExecutionContext is not thread safe, which is why it is created for every run.
No comments:
Post a Comment