Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.*;
import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.w3c.dom.Element;

public class Main {
    /**
     * Return array of elements from given path.
     * @param root   parent element
     * @param path path array ("/ElementName")
     * @return array of elements or null
     */
    public static List<Element> getElements(Element root, String[] path) {
        NodeList nodes = root.getElementsByTagName(path[0]);
        return getElements(nodes, path);
    }

    /**
     * Return array of elements from given path.
     * @param doc
     * @param path      path array ("/root/items/item")
     * @return
     */
    public static List<Element> getElements(Document doc, String[] path) {
        NodeList nodes = doc.getElementsByTagName(path[0]);
        return getElements(nodes, path);
    }

    public static List<Element> getElements(NodeList nodes, String[] path) {
        if (nodes == null)
            return null;

        for (int i = 1; i < path.length; i++) {
            Element element = (Element) nodes.item(0);
            if (element == null)
                break;
            nodes = element.getElementsByTagName(path[i]);
        }
        if ((nodes == null) || (nodes.getLength() < 1))
            return null;

        List<Element> list = new ArrayList<Element>();
        for (int i = 0; i < nodes.getLength(); i++) {
            Element element = (Element) nodes.item(i);
            list.add(element);
        }

        return (list.size() < 1 ? null : list);
    }
}