Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
// License as published by the Free Software Foundation; either

import java.util.regex.Pattern;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    private static final Pattern PATTERN_AMP = Pattern.compile("&", Pattern.LITERAL);
    private static final Pattern PATTERN_LT = Pattern.compile("<", Pattern.LITERAL);
    private static final Pattern PATTERN_GT = Pattern.compile(">", Pattern.LITERAL);
    private static final Pattern PATTERN_QUOT = Pattern.compile("\"", Pattern.LITERAL);
    private static final Pattern PATTERN_APOS = Pattern.compile("\'", Pattern.LITERAL);

    /**
     * Convert the given Document to an XML String.
     * <p>
     * This method is a simplified version of...
     * <p>
     * <code>
     *    ByteArrayOutputStream out = new ByteArrayOutputStream();
     *    javax.xml.Transformer transformer = TransformerFactory.newInstance().newTransformer();
     *    transformer.transform( new DOMSource( node ), new StreamResult( out ));
     *    return out.toString();
     * </code>
     * <p>
     * ...but not all platforms (eg. Android) support <code>javax.xml.transform.Transformer</code>.
     */

    public static String documentToString(Document document, boolean pretty) {

        // Nothing to do?

        if (document == null) {
            return "";
        }

        return nodeToString(document.getFirstChild(), pretty);
    }

    /**
     * See documentToString.
     */

    public static String nodeToString(Node node, boolean pretty) {

        return nodeToString(node, (pretty ? 0 : -1));
    }

    /**
     * Convert the given Node to an XML String.
     * <p>
     * This method is a simplified version of...
     * <p>
     * <code>
     *    ByteArrayOutputStream out = new ByteArrayOutputStream();<br/>
     *    javax.xml.Transformer transformer = TransformerFactory.newInstance().newTransformer();<br/>
     *    transformer.transform( new DOMSource( node ), new StreamResult( out ));<br/>
     *    return out.toString();
     * </code>
     * <p>
     * ...but not all platforms (eg. Android) support <code>javax.xml.transform.Transformer</code>.
     *
     * @param indent
     *            how much to indent the output. -1 for no indent.
     */

    private static String nodeToString(Node node, int indent) {

        // Text nodes

        if (node == null) {
            return null;
        }

        if (!(node instanceof Element)) {

            String value = node.getNodeValue();

            if (value == null) {
                return null;
            }

            return escapeForXml(value.trim());
        }

        // (use StringBuffer for J2SE 1.4 compatibility)

        StringBuffer buffer = new StringBuffer();

        // Open tag

        indent(buffer, indent);
        String nodeName = escapeForXml(node.getNodeName());
        buffer.append("<");
        buffer.append(nodeName);

        // Changing namespace

        String namespace = node.getNamespaceURI();
        Node parentNode = node.getParentNode();

        if (namespace != null && (parentNode == null || !namespace.equals(parentNode.getNamespaceURI()))) {
            buffer.append(" xmlns=\"");
            buffer.append(namespace);
            buffer.append("\"");
        }

        // Attributes

        NamedNodeMap attributes = node.getAttributes();

        // Always put name first for easy unit tests

        Node name = attributes.getNamedItem("name");

        if (name != null) {
            buffer.append(" name=\"");
            buffer.append(escapeForXml(name.getNodeValue()));
            buffer.append("\"");
        }

        for (int loop = 0; loop < attributes.getLength(); loop++) {
            Node attribute = attributes.item(loop);
            String attributeName = attribute.getNodeName();

            // (I'm a bit surprised xmlns is an attribute - is that a bug?)

            if ("xmlns".equals(attributeName)) {
                continue;
            }

            // (always put name first for easy unit tests)

            if ("name".equals(attributeName)) {
                continue;
            }

            buffer.append(" ");
            buffer.append(escapeForXml(attributeName));
            buffer.append("=\"");
            buffer.append(escapeForXml(attribute.getNodeValue()));
            buffer.append("\"");
        }

        // Children (if any)

        NodeList children = node.getChildNodes();
        int length = children.getLength();

        if (length == 0) {
            buffer.append("/>");
        } else {
            buffer.append(">");

            int nextIndent = indent;

            if (indent != -1) {
                nextIndent++;
            }

            for (int loop = 0; loop < length; loop++) {
                Node childNode = children.item(loop);

                if (indent != -1 && childNode instanceof Element) {
                    buffer.append("\n");
                }

                buffer.append(nodeToString(childNode, nextIndent));
            }

            if (indent != -1 && buffer.charAt(buffer.length() - 1) == '>') {
                buffer.append("\n");
                indent(buffer, indent);
            }

            // Close tag

            buffer.append("</");
            buffer.append(nodeName);
            buffer.append(">");
        }

        return buffer.toString();
    }

    private static String escapeForXml(String in) {

        if (in == null) {
            return "";
        }

        String out = in;

        out = PATTERN_AMP.matcher(out).replaceAll("&amp;");
        out = PATTERN_LT.matcher(out).replaceAll("&lt;");
        out = PATTERN_GT.matcher(out).replaceAll("&gt;");
        out = PATTERN_QUOT.matcher(out).replaceAll("&quot;");
        out = PATTERN_APOS.matcher(out).replaceAll("&apos;");

        return out;
    }

    private static void indent(StringBuffer buffer, int indent) {

        for (int loop = 0; loop < indent; loop++) {
            buffer.append("   ");
        }
    }
}