Java XML Node to String nodeToString(Node node, boolean pretty)

Here you can find the source of nodeToString(Node node, boolean pretty)

Description

See documentToString.

License

LGPL

Declaration


public static String nodeToString(Node node, boolean pretty) 

Method Source Code

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

import java.util.regex.Pattern;

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

    /**//w w w.j a v a  2s.  c o m
     * 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. nodeToString(Node node)
  2. nodeToString(Node node)
  3. nodeToString(Node node)
  4. nodeToString(Node node)
  5. nodeToString(Node node)
  6. nodeToString(Node node, Set parentPrefixes, String namespaceURI)
  7. nodeToString(Node node, StringBuffer buf)
  8. nodeToString(Node node, StringBuffer sb)
  9. nodeToString(Object node)