Java XML Node Remove removeWhitespaceNodes(Node e)

Here you can find the source of removeWhitespaceNodes(Node e)

Description

remove Whitespace Nodes

License

Open Source License

Declaration

private static void removeWhitespaceNodes(Node e) 

Method Source Code

//package com.java2s;
/*//from   www . ja v a2 s.c  o  m
* ? Copyright IBM Corp. 2011, 2014
* 
* 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;
import org.w3c.dom.Text;

public class Main {
    private static void removeWhitespaceNodes(Node e) {
        // called after have read-in the nodes. 
        // Later the nodeToString method will be used to 
        // convert the node to string, while attempting to format with 2-space indent.
        // But if the tree already contains whitespace characters then it won't do the indent formatting,
        // and you end up with a mix of tabs, 2-space and 4-space indenting.
        // So removing the source-file indentation whitespace here, so can do consistent 2-space indent.
        NodeList kids = e.getChildNodes();
        int i = 0;
        while (i < kids.getLength()) {
            Node kid = kids.item(i);
            if (kid.getNodeType() == Node.TEXT_NODE && ((Text) kid).getTextContent().trim().isEmpty()) {
                e.removeChild(kid);
            } else {
                if (kid.getNodeType() == Node.ELEMENT_NODE) {
                    removeWhitespaceNodes(kid);
                }
                i++;
            }
        }
    }
}

Related

  1. removeUndesiredContent(Node node)
  2. removeUserData(Node node, String key)
  3. removeValue(NamedNodeMap values, String name)
  4. removeWhitespace(Node node, boolean deep)
  5. removeWhitespace(Node parent)
  6. removeWhitespaceNodes(org.w3c.dom.Element e)
  7. removeWhitespaceTextNodes(Element parent)