Java XML Node Print prettyPrint(Node root)

Here you can find the source of prettyPrint(Node root)

Description

Can help debug Node objects from IIOMetadata#getAsTree(String) .

License

Open Source License

Parameter

Parameter Description
root a parameter

Declaration

static void prettyPrint(Node root) 

Method Source Code


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

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

public class Main {
    /**//from   www.j a  v a 2  s  . co  m
     * Can help debug Node objects from {@link IIOMetadata#getAsTree(String)}.
     * Not used in production.
     *
     * @param root
     */
    static void prettyPrint(Node root) {
        displayMetadata(root, 0);
    }

    private static void displayMetadata(Node node, int level) {
        // print open tag of element
        indent(level);
        System.out.print("<" + node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        if (map != null) {
            // print attribute values
            int length = map.getLength();
            for (int i = 0; i < length; i++) {
                Node attr = map.item(i);
                System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
            }
        }

        Node child = node.getFirstChild();
        if (child == null) {
            // no children, so close element and return
            System.out.println("/>");
            return;
        }

        // children, so close current tag
        System.out.println(">");
        while (child != null) {
            // print children recursively
            displayMetadata(child, level + 1);
            child = child.getNextSibling();
        }

        // print close tag of element
        indent(level);
        System.out.println("</" + node.getNodeName() + ">");
    }

    private static void indent(int level) {
        for (int i = 0; i < level; i++)
            System.out.print("    ");
    }
}

Related

  1. prettyPrintLoop(Node node, StringBuilder string, String indentation)
  2. prettyPrintNode(Node aNode, int indent)
  3. print(Node node)
  4. print(Node node)