get Child Element from XML Element - Java XML

Java examples for XML:XML Element Child

Description

get Child Element from XML Element

Demo Code


//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Element getChild(Element node, String tagName) {
        Element element = null;//from   ww  w .j ava2s .com

        do {
            if (node == null) {
                break;
            }

            NodeList childNodes = node.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node child = childNodes.item(i);

                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    if (child.getNodeName().equals(tagName)) {
                        element = (Element) child;
                        break;
                    }
                }
            }
        } while (false);

        return element;
    }
}

Related Tutorials