Recursively removes all text nodes from a XML DOM element. - Android XML

Android examples for XML:DOM

Description

Recursively removes all text nodes from a XML DOM element.

Demo Code

/**/* w w  w.  j av a 2s . c  om*/
 * Copyright 2011-2016 Three Crickets LLC.
 * <p>
 * The contents of this file are subject to the terms of the LGPL version 3.0:
 * http://www.gnu.org/copyleft/lesser.html
 * <p>
 * Alternatively, you can obtain a royalty free commercial license with less
 * limitations, transferable or non-transferable, directly from Three Crickets
 * at http://threecrickets.com/
 */
//package com.java2s;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
    /**
     * Recursively removes all text nodes from a DOM element.
     * 
     * @param element
     *        The element
     */
    public static void removeTextNodes(Element element) {
        Node nextNode = element.getFirstChild();
        for (Node child = element.getFirstChild(); nextNode != null;) {
            child = nextNode;
            nextNode = child.getNextSibling();
            if (child.getNodeType() == Node.TEXT_NODE)
                element.removeChild(child);
            else if (child.getNodeType() == Node.ELEMENT_NODE)
                removeTextNodes((Element) child);
        }
    }
}

Related Tutorials