Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

public class Main {
    private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();

    /**
     * Converts a {@link Node node} to an XML string
     *
     * @param node the first element
     * @return the XML String representation of the node, never null
     */
    public static String nodeToString(Node node) {
        try {
            StringWriter writer = new StringWriter();
            createIndentingTransformer().transform(new DOMSource(node), new StreamResult(writer));
            return writer.toString();
        } catch (TransformerException e) {
            throw new IllegalStateException(e);
        }
    }

    /**
     * @return a transformer that indents entries by 4 characters (never null)
     */
    public static final Transformer createIndentingTransformer() {
        Transformer transformer;
        try {
            transformerFactory.setAttribute("indent-number", 4);
            transformer = transformerFactory.newTransformer();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        return transformer;
    }
}