Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

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

public class Main {
    private final static String internal = " ";

    public static String retrieveDocumentAsString(Document doc) {
        Node node = doc.getDocumentElement();
        return retrieveNodeAsString(node);
    }

    public static String retrieveNodeAsString(Node node) {
        String nodeStr = new String("<");
        nodeStr += node.getNodeName() + internal;
        if (node.hasAttributes()) {
            NamedNodeMap attrs = node.getAttributes();
            // add the attrubite name-value pairs
            for (int i = 0; i < attrs.getLength(); i++) {
                Node a = attrs.item(i);
                nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal;
            }
        }

        if (node.hasChildNodes()) {
            nodeStr += ">\n";
            NodeList ns = node.getChildNodes();
            for (int i = 0; i < ns.getLength(); i++) {
                nodeStr += logXMLSubNode(ns.item(i), 1);
            }
            nodeStr += "<" + node.getNodeName() + "/>\n";
        } else {
            nodeStr += "/>\n";
        }
        return nodeStr;
    }

    private static String logXMLSubNode(Node node, int deepth) {

        int i;
        String nodeStr = new String();
        String interStr = new String();
        for (i = 0; i < deepth; i++)
            interStr += "\t";

        nodeStr += interStr + "<" + node.getNodeName() + internal;
        if (node.hasAttributes()) {
            NamedNodeMap attrs = node.getAttributes();

            // add the attrubite name-value pairs
            for (i = 0; i < attrs.getLength(); i++) {
                Node a = attrs.item(i);
                nodeStr += a.getNodeName() + "=" + a.getNodeValue() + internal;
            }
        }
        if (node.hasChildNodes()) {
            nodeStr += ">\n";
            NodeList ns = node.getChildNodes();
            for (i = 0; i < ns.getLength(); i++) {
                nodeStr += logXMLSubNode(ns.item(i), deepth + 1);
            }
            nodeStr += interStr + "</" + node.getNodeName() + ">\n";
        } else {
            if (node.getNodeValue() != null) {
                nodeStr += ">" + node.getNodeValue() + "<" + node.getNodeName();
            }
            nodeStr += "/>\n";
        }
        return nodeStr;
    }
}