Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.ByteArrayInputStream;

import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {
    /**
     * Applies an XSL transformation to <code>xmlString</code> using
     * <code>xsltStr</code> as the stylesheet and returns the transformed
     * string.
     * 
     * @param xmlString
     *            The XML to transform.
     * @param xsltStr
     *            The stylesheet as an XML string (not a file).
     * @return Transformed string.
     * @throws Exception
     */
    public static String applyStylesheetAsString(String xmlString, String xsltStr) throws Exception {
        // Use the static TransformerFactory.newInstance() method to instantiate
        // a TransformerFactory. The javax.xml.transform.TransformerFactory
        // system property setting determines the actual class to instantiate --
        // org.apache.xalan.transformer.TransformerImpl.

        TransformerFactory tFactory = TransformerFactory.newInstance();

        // Use the TransformerFactory to instantiate a Transformer that will work with
        // the stylesheet you specify. This method call also processes the
        // stylesheet into a compiled Templates object.

        Transformer transformer = tFactory
                .newTransformer(new StreamSource(new ByteArrayInputStream(xsltStr.getBytes())));

        // Use the Transformer to apply the associated Templates object to an
        // XML document (foo.xml) and write the output to a file (foo.out).

        StringWriter swriter = new StringWriter();
        StreamResult sresult = new StreamResult(swriter);
        transformer.transform(new StreamSource(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))), sresult);
        return swriter.toString();
    }
}