get Elements from XML Document by element name - Java XML

Java examples for XML:DOM Document

Description

get Elements from XML Document by element name

Demo Code


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

public class Main {
    public static ArrayList<Element> getElements(String elementName,
            Document doc) {//w w w .j a va2  s . c o  m
        ArrayList<Element> result = new ArrayList<Element>();
        NodeList list = doc.getElementsByTagName(elementName);

        for (int i = 0; i < list.getLength(); i++) {
            Node nNode = list.item(i);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                result.add((Element) nNode);
            }
        }
        return result;
    }

    public static ArrayList<Element> getElements(String elementName,
            Element element) {
        ArrayList<Element> result = new ArrayList<Element>();
        NodeList list = element.getElementsByTagName(elementName);

        for (int i = 0; i < list.getLength(); i++) {
            Node nNode = list.item(i);

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                result.add((Element) nNode);
            }
        }
        return result;
    }
}

Related Tutorials