Java XML Element Remove removeElements(Element from, String named)

Here you can find the source of removeElements(Element from, String named)

Description

Removes all children named named from element from

License

Apache License

Parameter

Parameter Description
from which to remove items named named
named is the name of the elements to remove from from

Declaration

public static void removeElements(Element from, String named) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import org.w3c.dom.*;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**/*from   www.  j av  a  2 s .c  o m*/
     * Removes all children named {@code named} from element {@code from}
     * @param from which to remove items named {@code named}
     * @param named is the name of the elements to remove from {@code from}
     */
    public static void removeElements(Element from, String named) {
        NodeList children = from.getChildNodes();
        boolean removeNextNewline = false;
        List<Node> removes = new ArrayList<Node>();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            if ((child != null) && named.equals(child.getNodeName())) {
                removes.add(child);
                removeNextNewline = true;
            } else if (removeNextNewline && (child != null) && (child instanceof Text)
                    && child.getNodeValue().trim().isEmpty()) {
                removes.add(child);
            } else {
                removeNextNewline = false;
            }
        }
        for (Node node : removes) {
            from.removeChild(node);
        }
    }
}

Related

  1. remove(Element element, Predicate shouldRemovePredicate)
  2. removeAll(Element node, String subElement)
  3. removeContent(Element element)
  4. removeEmptyElements(Node node)
  5. removePreviousSiblingText(Element element)
  6. removeSchemaLocation(Element el)
  7. removeTopPi(Element e, Element pi)