Java XML Node Print printTree(Node root, int level)

Here you can find the source of printTree(Node root, int level)

Description

print a text representation of the dom hierarchy.

License

MIT License

Parameter

Parameter Description
root document root node
level level to print to

Declaration

public static void printTree(Node root, int level) 

Method Source Code

//package com.java2s;
/** Copyright by Barry G. Becker, 2000-2011. Licensed under MIT License: http://www.opensource.org/licenses/MIT  */

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

public class Main {
    /**//www  .  j a  v a2  s .c om
     * print a text representation of the dom hierarchy.
     * @param root document root node
     * @param level level to print to
     */
    public static void printTree(Node root, int level) {
        NodeList l = root.getChildNodes();
        for (int i = 0; i < level; i++)
            System.out.print("    ");

        NamedNodeMap attribMap = root.getAttributes();
        String attribs = getAttributeList(attribMap);

        System.out.println("Node: <" + root.getNodeName() + ">  " + attribs);
        for (int i = 0; i < l.getLength(); i++) {
            printTree(l.item(i), level + 1);
        }
    }

    /**
     * a concatenated list of the node's attributes.
     * @param attributeMap maps names to nodes
     * @return list of attributes
     */
    public static String getAttributeList(NamedNodeMap attributeMap) {
        String attribs = "";
        if (attributeMap != null) {
            attributeMap.getLength();

            for (int i = 0; i < attributeMap.getLength(); i++) {
                Node n = attributeMap.item(i);
                attribs += n.getNodeName() + "=\"" + n.getNodeValue() + "\"  ";
            }
        }
        return attribs;
    }
}

Related

  1. printNodeIterator(NodeIterator iterator)
  2. printNodes(Node node, int level)
  3. printNodeType(Node node, int ident)
  4. printToTerminal(Node n, String indent, boolean descend)
  5. printTree(Node node, int ident)