Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.*;

public class Main {
    /** @param doc an XML document.
     *   @return a string representing the stringified version of that document, with minor pretty-printing.
     */

    public static String doc2String(Document doc) {
        //System.out.println("XMLUtils: converting doc to string");
        StringBuffer result = new StringBuffer();
        doc2String(doc.getFirstChild(), result, 0);
        return result.toString();
    }

    /**Recursive method which has a side effect of setting the result to the pretty-printed flat text version of an XML node.
     * @param finger the current node
     * @param result the resultant string that is being built up.
     * @param indent the current indenting level.
     */

    private static void doc2String(Node finger, StringBuffer result, int indent) {
        //Base Case
        for (int j = 0; j < indent; j++)
            result.append(' ');
        if (finger.getNodeType() == Node.TEXT_NODE) {
            result.append(finger.getNodeValue().trim());
            result.append("\n");
            return;
        }
        result.append('<');
        //System.out.println("XMLUtils: appending " + finger.getNodeName() + " to output");
        result.append(finger.getNodeName().trim());
        result.append('>');
        result.append("\n");
        if (finger.hasChildNodes()) {
            NodeList childList = finger.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                doc2String(childList.item(i), result, indent + 1);
            }
        }
        for (int j = 0; j < indent; j++)
            result.append(' ');
        result.append("</");
        //System.out.println("XMLUtils: appending end " + finger.getNodeName() + " to output");
        result.append(finger.getNodeName().trim());
        result.append('>');
        result.append("\n");
    }
}