Java XML Node to String toString(Node node)

Here you can find the source of toString(Node node)

Description

to String

License

Open Source License

Declaration

public static String toString(Node node) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.Document;

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

public class Main {
    public static String toString(Node node) {
        return nodeToString(node, 0);
    }/*from  w  ww.ja  v a2 s.  c  o  m*/

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

        if (node.getNodeType() == Node.DOCUMENT_NODE)
            node = ((Document) node).getDocumentElement();

        StringBuilder strb = new StringBuilder();
        NodeList childNodes = node.getChildNodes();
        String indent;

        for (int j = 0; j < deep; j++)
            strb.append("\t");
        indent = strb.toString();

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            strb.append("<").append(node.getNodeName());

            NamedNodeMap attr = node.getAttributes();
            for (int j = 0; j < attr.getLength(); j++) {
                strb.append(" ").append(attr.item(j).getNodeName()).append("=\"")
                        .append(attr.item(j).getNodeValue()).append("\"");
            }
            if (childNodes.getLength() > 0) {
                strb.append(">\n");
                for (int i = 0; i < childNodes.getLength(); i++) {
                    Node child = childNodes.item(i);
                    if (child.getNodeType() == Node.ELEMENT_NODE || child.getNodeType() == Node.TEXT_NODE) {
                        strb.append(nodeToString(child, deep + 1)).append("\n");
                    }
                }
                strb.append(indent).append("</").append(node.getNodeName()).append(">");
            } else
                strb.append(" />");
        } else if (node.getNodeType() == Node.TEXT_NODE) {
            strb.append(node.getTextContent());
        }

        return strb.toString();
    }
}

Related

  1. toString(Node n)
  2. toString(Node node)
  3. toString(Node node)
  4. toString(Node node)
  5. toString(Node node)
  6. toString(Node node)
  7. toString(Node node)
  8. toString(Node node)
  9. toString(Node node)