get Child Nodes By Name from XML Element - Java XML

Java examples for XML:XML Element Child

Description

get Child Nodes By Name from XML Element

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static Node[] getChildNodesByName(Element parent, String name) {
        List<Node> nodeList = new ArrayList<Node>();

        NodeList childNodes = parent.getChildNodes();
        int length = childNodes.getLength();
        for (int i = 0; i < length; i++) {
            Node current = childNodes.item(i);
            if (current.getNodeName().equals(name))
                nodeList.add(current);//  w  w  w. j  a va 2s .c om
        }

        Node[] nodes = new Node[nodeList.size()];
        nodeList.toArray(nodes);
        return nodes;
    }
}

Related Tutorials