Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;

public class Main {
    private static TransformerFactory transformerFactory;
    private static Transformer defaultTransformer;

    public static String transformDocToTextWithXslt(Document document, String xsltContent)
            throws TransformerConfigurationException, TransformerException {
        Transformer transformer = getTransformerFromText(xsltContent);
        return transformToStringResult(document, transformer);
    }

    private static Transformer getTransformerFromText(String xsltContent) throws TransformerConfigurationException {
        if (xsltContent == null) {
            return getDefaultTransformer();
        } else {
            checkTransformFactory();
            return transformerFactory.newTransformer(new StreamSource(new StringReader(xsltContent)));
        }
    }

    private static String transformToStringResult(Document document, Transformer transformer)
            throws TransformerConfigurationException, TransformerException {
        StringWriter stringWriter = new StringWriter();
        synchronized (transformer) {
            transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        }
        return stringWriter.toString();
    }

    private static Transformer getDefaultTransformer() throws TransformerConfigurationException {
        checkTransformFactory();
        if (defaultTransformer == null) {
            defaultTransformer = transformerFactory.newTransformer();
        }
        return defaultTransformer;
    }

    private static void checkTransformFactory() throws TransformerConfigurationException {
        if (transformerFactory == null) {
            transformerFactory = TransformerFactory.newInstance();
        }
    }
}