Java XML Element Remove remove(Element element, Predicate shouldRemovePredicate)

Here you can find the source of remove(Element element, Predicate shouldRemovePredicate)

Description

Removes child elements that meet a certain condition.

License

Open Source License

Parameter

Parameter Description
element The parent element.
shouldRemovePredicate The condition to test against. If true, the child item will be removed.

Declaration

public static void remove(Element element, Predicate<Element> shouldRemovePredicate) 

Method Source Code

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

import java.util.function.Predicate;

import org.w3c.dom.*;

public class Main {
    /**/*from   w  ww  .  j a va  2  s  .com*/
     * Removes child elements that meet a certain condition.
     *
     * @param element The parent element.
     * @param shouldRemovePredicate The condition to test against. If true, the child item will be removed.
     */
    public static void remove(Element element, Predicate<Element> shouldRemovePredicate) {
        NodeList childNodes = element.getChildNodes();
        int i = 0;
        while (i < childNodes.getLength()) {
            Node currentNode = childNodes.item(i);
            Element child = (currentNode instanceof Element) ? ((Element) currentNode) : null;
            if (child != null && shouldRemovePredicate.test(child)) {
                element.removeChild(currentNode);
            } else {
                i++;
            }
        }
    }
}

Related

  1. removeAll(Element node, String subElement)
  2. removeContent(Element element)
  3. removeElements(Element from, String named)
  4. removeEmptyElements(Node node)