Java XML Node Remove removeElements(Node parent, String nature)

Here you can find the source of removeElements(Node parent, String nature)

Description

Removes all elements with a given nature (as content).

License

Apache License

Parameter

Parameter Description
parent the parent node to start at
nature the nature as content to be removed

Declaration

private static void removeElements(Node parent, String nature) 

Method Source Code

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

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

public class Main {
    /** /*from   w  ww  .ja v  a2s  . co  m*/
     * Removes all elements with a given nature (as content).
     * 
     * @param parent the parent node to start at
     * @param nature the nature as content to be removed
     */
    private static void removeElements(Node parent, String nature) {
        NodeList children = parent.getChildNodes();
        //Go over all children
        for (int i = 0; i < children.getLength(); i++) {

            Node child = children.item(i);

            //only interested in elements  
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                // remove elements with matching content/nature  
                if (checkNature(child, nature)) {
                    parent.removeChild(child);
                } else {
                    removeElements(child, nature);
                }
            }
        }
    }

    /**
     * Checks whether the text content of the given <code>node</code> matches the given <code>nature</code>.
     * 
     * @param node the node to be checked
     * @param nature the nature to be considered
     * @return <code>true</code> if the nature is represented by <code>node</code>, <code>false</code> else
     */
    private static boolean checkNature(Node node, String nature) {
        return node.getTextContent().trim().equals(nature);
    }
}

Related

  1. removeAll(Node node)
  2. removeAll(Node node, short nodeType, String name)
  3. removeAll(Node node, short nodeType, String name)
  4. removeContents(Node parent)
  5. removeElement(Element parent, String tagName)
  6. removeElementXML(Node node, short nodeType, String name)
  7. removeEmptyHeadings(Node root)
  8. removeEmptyHeadings(Node root)
  9. removeEmptyLines(Node node)