Java XML Node Remove removeEmptyTextNodes(Node parentNode)

Here you can find the source of removeEmptyTextNodes(Node parentNode)

Description

Removes all empty or whitespace only text nodes from the given parent node.

License

Open Source License

Parameter

Parameter Description
parentNode the parent node to be cleared of empty or whitespace only text nodes

Declaration

private static void removeEmptyTextNodes(Node parentNode) 

Method Source Code

//package com.java2s;
/**// www. j a va 2 s .  com
 * Copyright (c) 2014 mediaworx berlin AG (http://mediaworx.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * For further information about mediaworx berlin AG, please see the
 * company website: http://mediaworx.com
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 * If not, see <http://www.gnu.org/licenses/>
 */

import org.w3c.dom.Node;

public class Main {
    /**
     * Removes all empty or whitespace only text nodes from the given parent node.
     * @param parentNode    the parent node to be cleared of empty or whitespace only text nodes
     */
    private static void removeEmptyTextNodes(Node parentNode) {
        Node childNode = parentNode.getFirstChild();
        while (childNode != null) {
            // grab the "nextSibling" before the child node is removed
            Node nextChild = childNode.getNextSibling();

            short nodeType = childNode.getNodeType();
            if (nodeType == Node.TEXT_NODE) {
                boolean containsOnlyWhitespace = childNode.getNodeValue()
                        .trim().isEmpty();
                if (containsOnlyWhitespace) {
                    parentNode.removeChild(childNode);
                }
            }
            childNode = nextChild;
        }
    }
}

Related

  1. removeEmptyHeadings(Node root)
  2. removeEmptyLines(Node node)
  3. removeEmptyNodes(Node node)
  4. removeEmptyParagraphs(Node root)
  5. removeEmptyTextNodes(Node parentNode)
  6. removeJavascripts(Node node)
  7. removeLeafNode(Node node)
  8. removeNamedItem(final NamedNodeMap nodeMap, final String name)
  9. removeNamespaceDeclarations(Node node, String... namespaces)