Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*--------------------------------------------------------------------------
 * Copyright (c) 2004, 2006 OpenMethods, LLC
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Trip Gilman (OpenMethods), Lonnie G. Pryor (OpenMethods),
 *    Vincent Pruitt (OpenMethods)
 *    
 *    T.D. Barnes (OpenMethods) - initial API and implementation
 -------------------------------------------------------------------------*/

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 {
    /**
     * Retrieves the DOM <code>NodeList</code> contained by the named element
     * in the given parent element.<br>
     * <br>
     * <pre>
     * <parent-element>
     *     <named-list>
     *         <list-item/>
     *         <list-item/>
     *     </named-list>
     * </parent-element>
     * </pre>
     * 
     * In the above example, a <code>NodeList</code> containing the two
     * <pre><list-item/></pre> elements would be returned by passing the parent
     * element and "named-list" into the function parameters.
     * 
     * @param parent The parent DOM element that contains the named list.
     * @param containerTagName The name of the element that contains the list items.
     * @return A <code>NodeList</code> containing the list items.
     * @throws Exception If an exception occurs while traversing the DOM objects.
     */
    public static NodeList getNamedNodeList(Element parent, String containerTagName) throws Exception {
        NodeList nl = parent.getElementsByTagName(containerTagName);

        if (nl.getLength() < 1) {
            throw new Exception("Missing named list: " + containerTagName);
        }

        return nl.item(0).getChildNodes();
    }

    public static List<Element> getElementsByTagName(Element parent, String name, boolean localOnly) {
        List<Element> ret = new ArrayList<Element>();
        if (!localOnly) {
            NodeList elementList = parent.getElementsByTagName(name);
            for (int i = 0; i < elementList.getLength(); i++) {
                ret.add((Element) elementList.item(i));
            }
        } else {
            NodeList childList = parent.getChildNodes();
            for (int i = 0; i < childList.getLength(); i++) {
                if (childList.item(i).getNodeType() != Node.ELEMENT_NODE)
                    continue;
                Element child = (Element) childList.item(i);
                if (child.getTagName().equals(name))
                    ret.add(child);
            }
        }
        return ret;
    }
}