Get the node set from XML parent node by the specified name - Java XML

Java examples for XML:XML Element Parent

Description

Get the node set from XML parent node by the specified name

Demo Code


//package com.java2s;

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

import java.util.ArrayList;

public class Main {
    /**//w  w  w .  j  a  va  2 s  . co  m
     * Get the node set from parent node by the specified  name
     *
     * @param parent
     * @param name
     * @return
     */
    public static Element[] getElementsByName(Element parent, String name) {
        ArrayList resList = new ArrayList();
        NodeList nl = getNodeList(parent);
        for (int i = 0; i < nl.getLength(); i++) {
            Node nd = nl.item(i);
            if (nd.getNodeName().equals(name)) {
                resList.add(nd);
            }
        }
        Element[] res = new Element[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[0] = (Element) resList.get(i);
        }
        return res;
    }

    /**
     * Get all child nodes of a parent node
     *
     * @param parent
     * @return
     */
    public static NodeList getNodeList(Element parent) {
        return parent.getChildNodes();
    }
}

Related Tutorials