Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

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

import java.io.StringWriter;

public class Main {
    /**
     * Format generated xml doc by indentation
     *
     * @param node   For java, rather than GWT
     * @param indent
     * @return
     */
    public static String format(Node node, String indent) {
        StringBuilder formatted = new StringBuilder();

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            StringBuilder attributes = new StringBuilder();
            for (int k = 0; k < node.getAttributes().getLength(); k++) {
                attributes.append(" ");
                attributes.append(node.getAttributes().item(k).getNodeName());
                attributes.append("=\"");
                attributes.append(node.getAttributes().item(k).getNodeValue());
                attributes.append("\"");
            }

            formatted.append(indent);
            formatted.append("<");
            formatted.append(node.getNodeName());
            formatted.append(attributes.toString());
            if (!node.hasChildNodes()) {
                formatted.append("/>\n");
                return formatted.toString();
            }
            if ((node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE)) {
                formatted.append(">");
            } else {
                formatted.append(">\n");
            }

            for (int i = 0; i < node.getChildNodes().getLength(); i++) {
                formatted.append(format(node.getChildNodes().item(i), indent + "   "));
            }

            if (node.hasChildNodes() && node.getFirstChild().getNodeType() != Node.TEXT_NODE) {
                formatted.append(indent);
            }
            formatted.append("</");
            formatted.append(node.getNodeName());
            formatted.append(">\n");
        } else {
            String value = node.getTextContent().trim();
            if (value.length() > 0) {
                formatted.append(value);
            }
        }
        return formatted.toString();
    }

    /** Transform a XML Document to String */
    public static String toString(Document doc) {
        try {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            return writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}