return an empty list if no child is found in XML Node - Java XML

Java examples for XML:XML Node Child

Description

return an empty list if no child is found in XML Node

Demo Code


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

import java.util.List;

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

public class Main {
    /**/*from   www .  j ava 2 s.  co m*/
     * return an empty list if no child is found
     * @param node
     * @param name
     * @return
     */
    public static List<Node> getChildren(Node node, String name) {
        List<Node> children = new ArrayList<Node>();
        if (!node.hasChildNodes())
            return children;
        NodeList lst = node.getChildNodes();
        if (lst == null)
            return children;
        for (int i = 0; i < lst.getLength(); i++) {
            Node child = lst.item(i);
            if (name.equals(child.getNodeName()))
                children.add(child);
        }

        return children;
    }
}

Related Tutorials