0

I'm new to XML so bear with me. I need to transform an xml file to another xml file. It needs xslt 2.0. I am using saxon's s9api. Using their documentation this what I have so far:

import java.io.File;
import javax.xml.transform.stream.StreamSource;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;
import net.sf.saxon.s9api.XsltTransformer;



class Main{
    public static void main(String args[]){

        Processor processor = new Processor(false);
        XsltCompiler compiler = processor.newXsltCompiler();
        DocumentBuilder builder = processor.newDocumentBuilder();
        try {
            builder.build(new File("C:\\XMLFILE.xml"));
        } catch (SaxonApiException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            XsltExecutable xsl = compiler.compile(new StreamSource(new File("C:\\XSLFILE.xsl")));
            XsltTransformer trans = xsl.load();
            trans.transform();


        } catch (SaxonApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

Is this the right direction? If it is and this is actually performing the transformation how do I specify the output xml.

1 Answer 1

0

You can set a destination on the transformer, for example an output File.

Serializer out = new Serializer();
out.setOutputProperty(Serializer.Property.METHOD, "html");
out.setOutputProperty(Serializer.Property.INDENT, "yes");
out.setOutputFile(new File("<filelocation>"));

Then set on the transformer

transformer.setDestination(out);

Before you make the call to transform().

trans.transform();
Sign up to request clarification or add additional context in comments.

5 Comments

I need to transform to xml. Can I just replace "html" with "xml"?
Also it give me the following error: Either a source document, an initial template or an initial function must be specified. Is that not what I did in the first try block?
You should also set the initial context node on your transformer. Your call to builder.build() should return a XdmNode. Set a local variable with the XdmNode (say source) and then set the initial context on the transformer transformer.setInitialContextNode(source).
To transform to xml, change the extension on the file your outputting to .xml and yes change the Serializer.Property.METHOD from "html" to "xml"
The Serializer constructor seems to be protected in 9.8.0 - you have to call the newSerializer() method of the Processor object to create it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.