get XML Child by name - Java XML

Java examples for XML:XML Element Child

Description

get XML Child by name

Demo Code


//package com.java2s;

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

public class Main {
    public static Node getChild(Node node, String name) {
        if (!node.hasChildNodes())
            return null;
        NodeList lst = node.getChildNodes();
        if (lst == null)
            return null;
        for (int i = 0; i < lst.getLength(); i++) {
            Node child = lst.item(i);
            if (name.equals(child.getNodeName()))
                return child;
        }/*from www  .  ja  v  a2s .  co m*/
        return null;
    }

    public static Node getChild(Node node, String name, String errMsg) {
        Node result = getChild(node, name);
        if (result == null) {
            throw new RuntimeException(errMsg
                    + ": missing mandatory attribute node '" + name + "'");
        }
        return result;
    }
}

Related Tutorials