Get first Child Element from XML Element - Java XML

Java examples for XML:XML Element Child

Description

Get first Child Element from XML Element

Demo Code


//package com.java2s;
import java.util.NoSuchElementException;

import org.w3c.dom.Element;

import org.w3c.dom.NodeList;

public class Main {
    public static Element firstChildElement(Element element,
            String childNameSpace, String childName)
            throws NoSuchElementException {
        NodeList childCandidateList;
        if (childNameSpace == null || childNameSpace.isEmpty()) {
            childCandidateList = element.getElementsByTagName(childName);
        } else {/*w w w.  j a v  a  2  s.  c  o  m*/
            childCandidateList = element.getElementsByTagNameNS(
                    childNameSpace, childName);
        }
        if (childCandidateList.getLength() > 0) {
            Element firstChild = (Element) childCandidateList.item(0);
            return firstChild;
        } else {
            throw new NoSuchElementException(
                    "No child candidate found in this element");
        }
    }

    public static Element firstChildElement(Element element,
            String childName) throws NoSuchElementException {
        return firstChildElement(element, null, childName);
    }
}

Related Tutorials