Java XML Has Child hasChild(Element element, String child)

Here you can find the source of hasChild(Element element, String child)

Description

Determine whether a single child is available of a particular type.

License

Open Source License

Exception

Parameter Description
Exception if the child is present multiple times.

Return

true if the specified child element is present

Declaration

public static boolean hasChild(Element element, String child) throws Exception 

Method Source Code

//package com.java2s;

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

public class Main {
    /**//from   ww w  . j  av  a  2  s .co  m
     * Determine whether a single child is available of a particular type.
     * @return true if the specified child element is present
     * @throws Exception if the child is present multiple times.
     */
    public static boolean hasChild(Element element, String child) throws Exception {
        NodeList nodes = element.getChildNodes();
        Element ret = null;
        for (int i = 0; i < nodes.getLength(); i++) {
            Node childNode = nodes.item(i);
            if (childNode.getNodeName().equals(child) && childNode.getNodeType() == Node.ELEMENT_NODE) {
                if (ret != null) {
                    throw new Exception("Child element '" + child + "' present multiple times");
                } else {
                    ret = (Element) childNode;
                }
            }
        }
        return ret != null;
    }
}

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 node, String name)
  6. hasChild(Element parent, String nodeName)
  7. hasChild(Element root, String childName)
  8. hasChild(Element start, String name)