Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.apache.log4j.Logger;

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

public class Main {
    /**
     * Output a DOM node including children using a log4j logger.
     * If logger is null it will just output to system out
     * 
     * @param logger
     * @param n
     */
    public static void outputNode(Logger logger, Node n) {
        outputNode(logger, n, 0);
    }

    /**
     * Output a DOM node including children to system out.
     * 
     * @param n
     */
    public static void outputNode(Node n) {
        outputNode(n, 0);
    }

    /**
     * Output a DOM node including children to system out 
     * indented by the number of tabs passed in.
     * 
     * @param n
     * @param tabs
     */
    public static void outputNode(Node n, int tabs) {
        outputNode(null, n, tabs);
    }

    /**
     * Output a DOM node including children using a log4j logger.
     * If logger is null it will just output to system out.
     * It will indent by the number of tabs passed in.
     * This method recursively calls itself to output
     * children nodes.
     * 
     * @param logger
     * @param n
     * @param tabs
     */
    public static void outputNode(Logger logger, Node n, int tabs) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < tabs; i++) {
            sb.append("\t");
        }
        sb.append("<" + n.getNodeName());

        if (n.hasAttributes()) {
            NamedNodeMap nnMap = n.getAttributes();
            for (int i = 0; i < nnMap.getLength(); i++) {
                Node att = nnMap.item(i);
                sb.append(" " + att.getNodeName() + "=\"" + att.getNodeValue() + "\"");
            }
        }
        sb.append(">");
        sb = printBuffer(logger, sb, true);

        for (int i = 0; i < tabs + 1; i++) {
            sb.append("\t");
        }
        sb.append(n.getNodeValue());
        sb = printBuffer(logger, sb, true);

        if (n.hasChildNodes()) {
            NodeList nodes = n.getChildNodes();
            for (int i = 0; i < nodes.getLength(); i++) {
                outputNode(nodes.item(i), tabs + 1);
            }
        }
        for (int i = 0; i < tabs; i++) {
            sb.append("\t");
        }
        sb.append("</" + n.getNodeName() + ">");
        sb = printBuffer(logger, sb, true);
    }

    private static StringBuffer printBuffer(Logger logger, StringBuffer sb, boolean clearBuffer) {
        if (logger != null) {
            logger.debug(sb.toString());
        } else {
            System.out.println(sb.toString());
        }
        if (clearBuffer)
            sb = new StringBuffer();
        return sb;
    }
}