Wednesday, May 23, 2012

Saxon in Java: XSLT for CSV to XML

Mostly continued from this question: XSLT: CSV (or Flat File, or Plain Text) to XML



So, I have an XSLT from here: http://andrewjwelch.com/code/xslt/csv/csv-to-xml_v2.html



And it converts a CSV file to an XML document. It does this when used with the following command on the command line:




java -jar saxon9he.jar -xsl:csv-to-xml.csv -it:main -o:output.xml




So now the question becomes: How do I do I do this in my Java code?



Right now I have code that looks like this:



TransformerFactory transformerFactory = TransformerFactory.newInstance();
StreamSource xsltSource = new StreamSource(new File("location/of/csv-to-xml.xsl"));
Transformer transformer = transformerFactory.newTransformer(xsltSource);
StringWriter stringWriter = new StringWriter();
transformer.transform(documentSource, new StreamResult(stringWriter));
String transformedDocument = stringWriter.toString().trim();


(The Transformer is an instance of net.sf.saxon.Controller.)



The trick on the command line is to specify "-it:main" to point right at the named template in the XSLT. This means you don't have to provide the source file with the "-s" flag.



The problem starts again on the Java side. Where/how would I specify this "-it:main"? Wouldn't doing so break other XSLT's that don't need that specified? Would I have to name every template in every XSLT file "main?" Given the method signature of Transformer.transform(), I have to specify the source file, so doesn't that defeat all the progress I've made in figuring this thing out?



Edit: I found the s9api hidden inside the saxon9he.jar, if anyone is looking for it.





No comments:

Post a Comment