Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.w3c.dom.Element;

public class Main {
    /** Holds the constructor to create an OutputFormat object. */
    private static Constructor<?> s_cOutputFormat;
    /** Holds the method OutputFormat.setIdent(). */
    private static Method s_mOFSetIndent;
    /** Holds the method OutputFormat.setIdenting(). */
    private static Method s_mOFSetIndenting;
    /** Holds the constructor to create the XMLSerializer. */
    private static Constructor<?> s_cXMLSerializer;
    /** Holds the method serialize. */
    private static Method s_mXSSerialize;

    /**
     * This method writes the XML into a nicely formatted string.
     * 
     * @param eRoot The root element.
     * @return The nicely formatted string.
     */
    public static String writePretty(Element eRoot) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        writePretty(eRoot, baos);

        return new String(baos.toByteArray());
    }

    /**
     * This method writes the XML into a nicely formatted string.
     * 
     * @param eRoot The root element.
     * @param osOutput The stream to write the data to.
     */
    public static void writePretty(Element eRoot, OutputStream osOutput) {
        Object of;

        try {
            of = s_cOutputFormat.newInstance(new Object[] { eRoot.getOwnerDocument() });

            s_mOFSetIndent.invoke(of, new Object[] { 4 });
            s_mOFSetIndenting.invoke(of, new Object[] { true });

            Object xs = s_cXMLSerializer.newInstance(new Object[] { osOutput, of });

            s_mXSSerialize.invoke(xs, new Object[] { eRoot });
        } catch (Exception e) {
            throw new RuntimeException("Error writing the XML to a pretty format", e);
        }
    }
}