Java XML Has Child hasChild(Element node, String name)

Here you can find the source of hasChild(Element node, String name)

Description

This method checks whether the given element node has a child element with the given name.

License

Open Source License

Parameter

Parameter Description
node - parent to check
name - name of child

Return

- true if parent has a child with the given name, false otherwise

Declaration

public static boolean hasChild(Element node, String name) 

Method Source Code

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

import java.util.*;

import org.w3c.dom.*;

public class Main {
    private static final String DOM_WILDCARD = "*";

    /**// ww w  .j a va2 s  .c  om
     * This method checks whether the given element node has a child element with the given name.
     * @param node - parent to check
     * @param name - name of child
     * @return - true if parent has a child with the given name, false otherwise
     */
    public static boolean hasChild(Element node, String name) {
        List<Element> children = getDirectChildElementsByTag(node, DOM_WILDCARD);
        for (Element e : children) {
            if (e.getNodeName().equals(name)) {
                return true;
            }
        }
        return false;
    }

    /**
     * This method returns a list of the direct element node children of this element node with the specified tag.
     * @param node - parent node
     * @param tag - tag of direct children to be returned
     * @return a list containing the direct element children with the given tag
     * @author Tristan Bepler
     */
    public static List<Element> getDirectChildElementsByTag(Element node, String tag) {
        List<Element> children = new ArrayList<Element>();
        Node child = node.getFirstChild();
        while (child != null) {
            if (child.getNodeType() == Node.ELEMENT_NODE
                    && (child.getNodeName().equals(tag) || tag.equals(DOM_WILDCARD))) {
                children.add((Element) child);
            }
            child = child.getNextSibling();
        }
        return children;
    }
}

Related

  1. getChildHash(Element elem, String elementName, String attrName)
  2. getLastVisibleChildElement(Node parent, Hashtable hiddenNodes)
  3. hasActivityChildNode(Node node)
  4. hasAnyChildElement(final Element e)
  5. hasChild(Element element, String child)
  6. hasChild(Element parent, String nodeName)
  7. hasChild(Element root, String childName)
  8. hasChild(Element start, String name)
  9. hasChild(Node n)