Example usage for javax.xml.transform TransformerFactory newTemplates

List of usage examples for javax.xml.transform TransformerFactory newTemplates

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory newTemplates.

Prototype

public abstract Templates newTemplates(Source source) throws TransformerConfigurationException;

Source Link

Document

Process the Source into a Templates object, which is a a compiled representation of the source.

Usage

From source file:Main.java

public static Document formatXML(Document xml, Document xsl) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    DOMSource xslSource = new DOMSource(xsl);
    Templates t = factory.newTemplates(xslSource);
    Transformer transformer = t.newTransformer();
    return formatXML(xml, transformer);
}

From source file:Main.java

public static void formatXML(Document xml, URIResolver resolver, Document xsl, Writer output) throws Exception {
    StreamResult result = new StreamResult(output);
    DOMSource xslSource = new DOMSource(xsl);
    TransformerFactory factory = TransformerFactory.newInstance();
    DOMSource xmlSource = new DOMSource(xml);
    Templates t = factory.newTemplates(xslSource);
    Transformer transformer = t.newTransformer();
    transformer.setURIResolver(resolver);
    transformer.transform(xmlSource, result);
}

From source file:Main.java

public static Document format(Source xslSource, Document xml, URIResolver resolver)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, Exception,
        TransformerException {//from  w  w w.  j  a  v  a  2  s . co  m
    TransformerFactory factory = TransformerFactory.newInstance();
    DOMSource xmlSource = new DOMSource(xml);
    Templates t = factory.newTemplates(xslSource);
    Transformer transformer = t.newTransformer();
    transformer.setURIResolver(resolver);
    Document resultDoc = newDocument();
    DOMResult result = new DOMResult(resultDoc);
    transformer.transform(xmlSource, result);
    return resultDoc;
}

From source file:Main.java

public static Templates TrAXPath(String xpath) throws TransformerConfigurationException {
    StringBuffer sb = new StringBuffer();

    // Create stylesheet that copies matching nodes
    sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    sb.append("<xsl:stylesheet version=\"1.0\" ");
    sb.append(" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
    sb.append("<xsl:output method=\"xml\" indent=\"yes\"/>");
    sb.append("<xsl:template match=\"" + xpath + "\">");
    sb.append("<xsl:copy-of select=\".\"/>");
    sb.append("</xsl:template>");
    sb.append("<xsl:template match=\"*|@*|text()\">");
    sb.append("<xsl:apply-templates />");
    sb.append("</xsl:template>");
    sb.append("</xsl:stylesheet>");

    // Construct the stylesheet Templates object.
    TransformerFactory tf = TransformerFactory.newInstance();
    String stylesheet = sb.toString();
    java.io.Reader r = new java.io.StringReader(stylesheet);
    StreamSource ssrc = new StreamSource(r);

    // Create templates object
    return tf.newTemplates(ssrc);
}

From source file:Main.java

public static Templates getTemplatesByName(File xslF) {

    Templates templates = null;/*from   w  ww.  j  a  v a 2 s .  com*/
    TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setAttribute("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE);

    InputStream is = null;
    try {
        StreamSource ss = new StreamSource(xslF);
        is = ss.getInputStream();
        templates = tfactory.newTemplates(ss);
        if (is != null) {
            is.close();
            is = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
                is = null;
            }
        } catch (Throwable t) {
            System.out.println(t);
        }
    }

    return templates;
}

From source file:Main.java

public static Document formatXML(Document xml, URIResolver resolver, String... xsls) throws Exception {
    TransformerFactory factory = TransformerFactory.newInstance();
    for (String xsl : xsls) {
        DOMSource xmlSource = new DOMSource(xml);
        Source xslSource = resolver.resolve(xsl, "");
        Templates t = factory.newTemplates(xslSource);
        Transformer transformer = t.newTransformer();
        transformer.setURIResolver(resolver);
        Document resultDoc = newDocument();
        DOMResult result = new DOMResult(resultDoc);
        transformer.transform(xmlSource, result);
        xml = resultDoc;/*from  w ww  .  j  a v a  2s  .  co  m*/
    }
    return xml;
}

From source file:edu.harvard.hul.ois.fits.Fits.java

public static void outputStandardSchemaXml(FitsOutput fitsOutput, OutputStream out)
        throws XMLStreamException, IOException {
    XmlContent xml = fitsOutput.getStandardXmlContent();

    //create an xml output factory
    Transformer transformer = null;

    //initialize transformer for pretty print xslt
    TransformerFactory tFactory = TransformerFactory.newInstance();
    String prettyPrintXslt = FITS_XML + "prettyprint.xslt";
    try {//from   w  w w.j  av  a  2s .  c o  m
        Templates template = tFactory.newTemplates(new StreamSource(prettyPrintXslt));
        transformer = template.newTransformer();
    } catch (Exception e) {
        transformer = null;
    }

    if (xml != null && transformer != null) {

        xml.setRoot(true);
        ByteArrayOutputStream xmlOutStream = new ByteArrayOutputStream();
        OutputStream xsltOutStream = new ByteArrayOutputStream();

        try {
            //send standard xml to the output stream
            XMLStreamWriter sw = xmlOutputFactory.createXMLStreamWriter(xmlOutStream);
            xml.output(sw);

            //convert output stream to byte array and read back in as inputstream
            Source source = new StreamSource(new ByteArrayInputStream(xmlOutStream.toByteArray()));
            Result rstream = new StreamResult(xsltOutStream);

            //apply the xslt
            transformer.transform(source, rstream);

            //send to the providedOutpuStream
            out.write(xsltOutStream.toString().getBytes("UTF-8"));
            out.flush();

        } catch (Exception e) {
            System.err.println("error converting output to a standard schema format");
        } finally {
            xmlOutStream.close();
            xsltOutStream.close();
        }

    } else {
        System.err.println("Error: output cannot be converted to a standard schema format for this file");
    }
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*from  w  w  w  .  j a v  a  2s  . co m*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:Examples.java

/**
 * Show how to override output properties.
 *///from   w ww  .j av  a  2  s .  c om
public static void exampleOutputProperties(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {

    TransformerFactory tfactory = TransformerFactory.newInstance();
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));
    Properties oprops = templates.getOutputProperties();

    oprops.put(OutputKeys.INDENT, "yes");

    Transformer transformer = templates.newTransformer();

    transformer.setOutputProperties(oprops);
    transformer.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}

From source file:Examples.java

/**
 * This shows how to set a parameter for use by the templates. Use 
 * two transformers to show that different parameters may be set 
 * on different transformers.//from  w  ww. ja  v a2 s.c om
 */
public static void exampleParam(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();
    Templates templates = tfactory.newTemplates(new StreamSource(xslID));
    Transformer transformer1 = templates.newTransformer();
    Transformer transformer2 = templates.newTransformer();

    transformer1.setParameter("a-param", "hello to you!");
    transformer1.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));

    System.out.println("\n=========");

    transformer2.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer2.transform(new StreamSource(sourceID), new StreamResult(new OutputStreamWriter(System.out)));
}