Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*******************************************************************************
 * Copyright 2012 Geoscience Australia
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

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

public class Main {
    /**
     * Remove any whitespace text nodes from the DOM. Calling this before saving
     * a formatted document will fix the formatting indentation of elements
     * loaded from a different document.
     * 
     * @param node
     *            Node to remove whitespace nodes from
     * @param deep
     *            Should this method recurse into the node's children?
     */
    public static void removeWhitespace(Node node, boolean deep) {
        NodeList children = node.getChildNodes();
        int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() == Node.TEXT_NODE && length > 1) {
                Node previous = child.getPreviousSibling();
                Node next = child.getNextSibling();
                if ((previous == null || previous.getNodeType() == Node.ELEMENT_NODE
                        || previous.getNodeType() == Node.COMMENT_NODE)
                        && (next == null || next.getNodeType() == Node.ELEMENT_NODE
                                || next.getNodeType() == Node.COMMENT_NODE)) {
                    String content = child.getTextContent();
                    if (content.matches("\\s*")) //$NON-NLS-1$
                    {
                        node.removeChild(child);
                        i--;
                        length--;
                    }
                }
            } else if (deep && child.getNodeType() == Node.ELEMENT_NODE) {
                removeWhitespace(child, deep);
            }
        }
    }
}