Java XML Node Print prettyPrintNode(Node aNode, int indent)

Here you can find the source of prettyPrintNode(Node aNode, int indent)

Description

pretty Print Node

License

Open Source License

Declaration

private static String prettyPrintNode(Node aNode, int indent) 

Method Source Code

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

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

public class Main {
    private static String prettyPrintNode(Node aNode, int indent) {
        StringBuilder str = new StringBuilder();
        if (aNode.getNodeType() == Node.ELEMENT_NODE) {
            String uri = aNode.getNamespaceURI() == null ? "" : (" xmlns=\"" + aNode.getNamespaceURI() + "\"");
            StringBuilder attrs = new StringBuilder();
            NamedNodeMap attrss = aNode.getAttributes();
            for (int k = 0; k < attrss.getLength(); k++) {
                Node atr = attrss.item(k);
                attrs.append(" " + atr.getNodeName() + "=\"" + atr.getNodeValue() + "\"");
            }//w ww  . j  a  va  2s .c o m
            for (int j = 0; j < indent; j++) {
                str.append(" ");
            }
            NodeList children = aNode.getChildNodes();
            if (children.getLength() > 0) {
                str.append("<" + aNode.getNodeName() + attrs.toString() + uri + ">\n");

                for (int i = 0; i < children.getLength(); i++) {
                    Node node = children.item(i);
                    str.append(prettyPrintNode(node, indent + 2));
                }
                for (int j = 0; j < indent; j++) {
                    str.append(" ");
                }
                str.append("</" + aNode.getNodeName() + ">\n");
            } else {
                str.append("<" + aNode.getNodeName() + attrs.toString() + uri + "/>\n");
            }
        } else {//TEXT_NODE
            for (int j = 0; j < indent; j++) {
                str.append(" ");
            }
            str.append(aNode.getNodeValue()).append("\n");
        }
        return str.toString();
    }
}

Related

  1. prettyPrint(Node root)
  2. prettyPrintLoop(Node node, StringBuilder string, String indentation)
  3. print(Node node)
  4. print(Node node)
  5. printArrayContent(Node[] t)
  6. printDifferences(Node node1, Node node2)