get XML Element Containers - Java XML

Java examples for XML:DOM Element

Description

get XML Element Containers

Demo Code


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

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

public class Main {
    public final static List<Node> getElementContainers(Element rootElement) {
        ArrayList<Node> elementList = new ArrayList<Node>();
        // we don't want to find all nodes named "elements", only the immediate
        // children of the root so named
        for (Node child : getChildElements(rootElement)) {
            if ("elements".equals(getElementName(child))) {
                elementList.add(child);/*from   w w  w  .jav a 2  s  .  c  om*/
            }
        }
        return elementList;
    }

    public final static List<Node> getChildElements(Node element) {
        ArrayList<Node> childList = new ArrayList<Node>();
        for (int i = 0; i < element.getChildNodes().getLength(); i++) {
            Node child = element.getChildNodes().item(i);
            if (Node.ELEMENT_NODE == child.getNodeType()) {
                childList.add(child);
            }
        }
        return childList;
    }

    public final static String getElementName(Node child) {
        return child.getNodeName();
    }
}

Related Tutorials