Java XML Document to String documentToString(Document document, boolean pretty)

Here you can find the source of documentToString(Document document, boolean pretty)

Description

Convert the given Document to an XML String.

License

LGPL

Declaration


public static String documentToString(Document document, boolean pretty) 

Method Source Code

//package com.java2s;
// Metawidget (licensed under LGPL)

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);

    /**/*from ww  w.  ja  v a 2s .  com*/
     * 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());
        }

        StringBuilder builder = new StringBuilder();

        // Open tag

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

        // Changing namespace

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

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

        // Attributes

        NamedNodeMap attributes = node.getAttributes();

        // Always put name first for easy unit tests

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

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

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

            // (never xmlns)

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

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

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

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

        // Children (if any)

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

        if (length == 0) {
            builder.append("/>");
        } else {
            builder.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) {
                    builder.append("\n");
                }

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

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

            // Close tag

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

        return builder.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(StringBuilder builder, int indent) {

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

Related

  1. documentToString(Document document)
  2. documentToString(Document document)
  3. documentToString(Document document)
  4. documentToString(Document document)
  5. documentToString(Document document)
  6. documentToString(Document document, boolean standalone)
  7. documentToString(Document document, Transformer documentTransformer)
  8. DocumentToString(Document dom)
  9. documentToString(final Node node)