Project

Profile

Help

Support #3237 » Program.java

Aniruddha Joag, 2017-05-25 17:44

 
package test.saxon.streaming.transformerhandler;

import com.saxonica.config.EnterpriseConfiguration;
import com.saxonica.config.StreamingTransformerFactory;

import javax.xml.transform.*;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;

public class Program
{

private static final String strXslt =
"<xsl:stylesheet version=\"3.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" >\n" +
" <xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/>\n" +
" <xsl:mode streamable=\"yes\" on-no-match=\"shallow-skip\"/>\n" +
" <xsl:mode name=\"row\" streamable=\"no\"/>\n" +
"\n" +
" <xsl:template match=\"/\">\n" +
" <rows>\n" +
" <xsl:apply-templates select=\"copy-of(rows/row)\" mode=\"row\"/>\n" +
" </rows>\n" +
" </xsl:template>\n" +
"\n" +
" <xsl:template match=\"row\" mode=\"row\">\n" +
" <row>\n" +
" <x-name><xsl:value-of select=\"name\"/></x-name>\n" +
" <x-id><xsl:value-of select=\"id\"/></x-id>\n" +
" </row>\n" +
" </xsl:template>\n" +
"\n" +
"</xsl:stylesheet>";

private static final int NUM_ROWS = 10;
private static final String RESULT_FILE = "C://swdtools/delete_later/forwarding.xml";

//private static final int NUM_ROWS = 100;
public static void main(String[] args) throws TransformerException, FileNotFoundException
{
//straightTransform();
forwardingHandlerTransform();
}

private static void straightTransform() throws TransformerException
{
SAXSource saxSource = new SAXSource(new RowXMLReader(NUM_ROWS), null);
Result result = new StreamResult(System.out);
getTransformer(strXslt).transform(saxSource, result);
}

private static void forwardingHandlerTransform() throws TransformerException, FileNotFoundException
{
final String newXslt = strXslt.replace("x-", "y-").replace("\"name\"", "\"x-name\"").replace("\"id\"", "\"x-id\"");
final Transformer transformer = getTransformer(newXslt);

//Result result = new StreamResult(System.out);
StreamResult streamResult = new StreamResult(new NonCloseFileOutputStream(new File(RESULT_FILE)));
ContentHandlerForwarder contentHandlerForwarder = new ContentHandlerForwarder(transformer, streamResult);
SAXResult transformedResultForwarder = new SAXResult(contentHandlerForwarder);
SAXSource saxSource = new SAXSource(new RowXMLReader(NUM_ROWS), null);
getTransformer(strXslt).transform(saxSource, transformedResultForwarder);
}


private static Transformer getTransformer(String stringXslt) throws TransformerConfigurationException
{
final StreamingTransformerFactory transformerFactory = new StreamingTransformerFactory(new EnterpriseConfiguration());
return transformerFactory.newTransformer(new StreamSource(new StringReader(stringXslt)));
}
}
(3-3/15)