0
votes

I'm trying to translate this command line code (which takes a .csv file and converts to xml through an xslt file and this works) to Java code: java -jar saxon9he.jar -xsl:"csv2xml.xslt" flatfile=input.csv -s:dummy.xml > output.txt

//Java Code using Saxon-HE 9.5: public static void transformFileUsingStyleSheet(String csvFile, String xslID) throws TransformerException {

    // Create a transform factory instance.
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Create a transformer for the stylesheet.
    Transformer transformer =
        tfactory.newTransformer(new StreamSource(xslID));

    // Transform the source XML to System.out.
    transformer.transform(new StreamSource(csvFile),
                          new StreamResult(new File("ConvertedCSV2XML.xml")));

}

But I'm getting this error when calling the above java method: SXXP0003: Error reported by XML parser: Content is not allowed in prolog like this: transformFileUsingStyleSheet("input.csv","csv2xml.xslt.xslt");

2
The file you're transforming must be well-formed XML. What I would do is pass the XSLT file itself as input (or still use dummy.xml) and the CSV as an xsl:param. You can read the CSV for processing with unparsed-text(). (That's what appears to be happening anyway based on the command line.)Daniel Haley

2 Answers

0
votes

The command line you have posted suggests that the Xslt takes a parameter named flatfile you have to set before running the transformation so make sure you do that in your Java code as well, should be transformer.setParameter("flatfile", csvFile). And as already pointed out in a comment, the command lines passes in a dummy.xml Xml input document, if you want to use the Transformer API you need to do this as well so make sure you pass in a third parameter inputFile with e.g. dummy.xml and then use transformer.transform(new StreamSource(inputFile), ..) as the first argument to the transform method.

However, note that Saxon has its own Api that allows you to run a stylesheet starting with a named template without needing a dummy XML input file.

0
votes

The JAXP transformation API is designed for XSLT 1.0, which requires an XML document as the principal source document. You will either need to supply a dummy source document (XML) to satisfy the API, or use Saxon's s9api API which gives full access to XSLT 2.0 (and XSLT 3.0) capabilities.