Thursday 10 July 2008

XSLT in Java with Oracle Parser part 2

Earlier I explained how to do an XSLT transformation using the Oracle Parser: http://darwin-it.blogspot.com/2008/06/xslt-in-java-with-oracle-parser.html.
I also created a Java Swing application to do transformations. I unfortunately found that my transformations did not went as expected. I'm busy with doing an XML to HTML transformation and my HTML tags did not get transformed. It works fine when the result of the transformation is just plain text.

The problem lies in the use of a XMLDocumentFragment as a result type of the xslProcessor.processXSL XSL processing. It took me a while to find a solution, since I have the requirement that the result gets into a String.

The xslProcessor has some processXSL methods that output to for example a URL or a PrintWriter. But how to get that into a String again?

Luckily today I found the solution. You have to wrap a StringWriter into a PrintWriter. Then give the PrintWriter to processXSL. Then after closing both, you can simply do a toString of the StringWriter. It looks like this:

public String transform(XMLDocument xslDoc, XMLDocument xmlDoc) {
XSLProcessor xslProcessor = new XSLProcessor();
XSLStylesheet xslt;
String result = "";
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
xslt = xslProcessor.newXSLStylesheet(xslDoc);
xslProcessor.setXSLTVersion(xslProcessor.XSLT20);
xslProcessor.showWarnings(true);
xslProcessor.setErrorStream(System.err);
xslProcessor.processXSL(xslt, xmlDoc, pw);
pw.flush();
pw.close();
sw.close();
result = sw.toString();
} catch (XSLException e) {
pl(e.toString());
} catch (IOException e) {
pl(e.toString());
}
return result;
}


I adapted it to my XMLTester tool that I just uploaded here.

No comments :