Java XML Child Get getChild(Element element, String child)

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

Description

get Child

License

Open Source License

Parameter

Parameter Description
child a parameter

Exception

Parameter Description
Exception if the child is present multiple times

Return

the single child element or null

Declaration

public static Element getChild(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 {
    /**//  ww  w  .  j a v  a  2 s.  c  o m
     * @param child
     * @return the single child element or null
     * @throws Exception if the child is present multiple times
     */
    public static Element getChild(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().equalsIgnoreCase(child) && childNode.getNodeType() == Node.ELEMENT_NODE) {
                if (ret != null) {
                    throw new Exception("Child element '" + child + "' present multiple times");
                } else {
                    ret = (Element) childNode;
                }
            }
        }
        if (ret == null) {
            return null;
        } else {
            return ret;
        }
    }
}

Related

  1. getChild(Element el, String name)
  2. getChild(Element element, String name)
  3. getChild(Element element, String name)
  4. getChild(Element element, String name)
  5. getChild(Element node, String tagName)