Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.*;

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

public class Main {
    private static TransformerFactory tf = null;

    /**
     * This method takes an XML Document, and converts it to a String for you.
     * @param doc The XML Document to be converted to a String.
     * @return The XML String that represents the Document.
     * @throws TransformerConfigurationException
     * @throws TransformerException
     *
     * @author <a href='mailto:intere@gmail.com'>Eric Internicola</a>
     */
    public static String toString(Document doc) throws TransformerConfigurationException, TransformerException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeDocument(doc, out);

        return out.toString();
    }

    /**
     * This method writes the provided XML Document to the provided OutputStream.
     * @param doc The XML Document to write to the stream.
     * @param out The OutputStream to write to.
     * @throws TransformerConfigurationException
     * @throws TransformerException
     *
     * @author <a href='mailto:intere@gmail.com'>Eric Internicola</a>
     */
    public static void writeDocument(Document doc, OutputStream out)
            throws TransformerConfigurationException, TransformerException {
        Transformer t = getNewTransformer();

        DOMSource ds = new DOMSource(doc);
        StreamResult sr = new StreamResult(out);
        t.transform(ds, sr);
    }

    /**
     * This method gives you a new Transformer Instance.
     * @return A new Transformer object instance.
     * @throws TransformerConfigurationException
     *
     * @author <a href='mailto:intere@gmail.com'>Eric Internicola</a>
     */
    private static Transformer getNewTransformer() throws TransformerConfigurationException {
        return getTransformerFactory().newTransformer();
    }

    /**
     * This method gives you the Transformer Factory (and creates it if necessary).
     * @return The TransformerFactory object instance.
     *
     * @author <a href='mailto:intere@gmail.com'>Eric Internicola</a>
     */
    private static synchronized TransformerFactory getTransformerFactory() {
        if (tf == null) {
            tf = TransformerFactory.newInstance();
        }

        return tf;
    }
}