Java XML Node Remove removeEmptyLines(Node node)

Here you can find the source of removeEmptyLines(Node node)

Description

Remove empty lines which are a descendant of node

License

Open Source License

Parameter

Parameter Description
node the initial node

Declaration

public static void removeEmptyLines(Node node) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.HashSet;

import java.util.Set;

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

public class Main {
    /**/*from w  w  w  .  j  av  a 2s  . co m*/
     * Remove empty lines which are a descendant of node
     * @param node the initial node
     */
    public static void removeEmptyLines(Node node) {
        Set<Node> nodesToRemove = new HashSet<Node>();
        collectEmptyLines(node, nodesToRemove);
        for (Node n : nodesToRemove) {
            n.getParentNode().removeChild(n);
        }
    }

    /**
     * Collect the empty lines to remove
     * @param node the parent node
     * @param nodesToRemove the set containing the nodes to remove
     */
    private static void collectEmptyLines(Node node, Set<Node> nodesToRemove) {
        if (node != null) {
            NodeList list = node.getChildNodes();
            int length = getNodeListLength(list);
            for (int i = 0; i < length; i++) {
                Node n = list.item(i);
                if (n != null) {
                    if (n.getNodeType() == Node.TEXT_NODE) {
                        nodesToRemove.add(n);
                    } else {
                        collectEmptyLines(n, nodesToRemove);
                    }
                }
            }
        }
    }

    /**
     * @param list a node list
     * @return the length
     */
    private static int getNodeListLength(NodeList list) {
        int length = 0;
        try {
            length = list.getLength();
        } catch (NullPointerException e) {
            /* Avoid Java bug */
        }
        return length;
    }
}

Related

  1. removeElement(Element parent, String tagName)
  2. removeElements(Node parent, String nature)
  3. removeElementXML(Node node, short nodeType, String name)
  4. removeEmptyHeadings(Node root)
  5. removeEmptyHeadings(Node root)
  6. removeEmptyNodes(Node node)
  7. removeEmptyParagraphs(Node root)
  8. removeEmptyTextNodes(Node parentNode)
  9. removeEmptyTextNodes(Node parentNode)