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.Document;

import org.w3c.dom.Node;

public class Main {
    private static String printNodeOnly(Node node) {
        return printXMLNode(node.cloneNode(false));
    }

    public static String printXMLNode(Node node) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setAttribute("indent-number", 2);
            Transformer transformer = tf.newTransformer();
            String omitDeclaration = node instanceof Document
                    || node == node.getOwnerDocument().getDocumentElement() ? "no" : "yes";
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitDeclaration);
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(node), new StreamResult(writer));
            String output = writer.getBuffer().toString();
            output = removeEmptyLines(output); // .replaceAll("\n|\r", "");
            return output;
        } catch (TransformerException te) {
            throw new RuntimeException(te);
        }
    }

    private static String removeEmptyLines(String text) {
        StringBuffer buffer = new StringBuffer();
        String[] lines = text.split("\n");
        for (String string : lines) {
            if (string.trim().isEmpty()) {
                continue;
            }
            buffer.append(string + "\n");
        }
        return buffer.toString();
    }
}