Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

import java.util.*;

import org.w3c.dom.*;

public class Main {
    /**
     * Looks through all child elements of the specified root (recursively) and
     * returns the elements that corresponds to all parameters.
     *
     * @param root the Element where the search should begin
     * @param tagName the name of the node we're looking for
     * @param keyAttributeName the name of an attribute that the node has to
     *            have
     * @param keyAttributeValue the value that attribute must have
     * @return list of Elements in the tree under root that match the specified
     *         parameters.
     * @throws NullPointerException if any of the arguments is null.
     */
    public static List<Element> locateElements(Element root, String tagName, String keyAttributeName,
            String keyAttributeValue) {
        List<Element> result = new ArrayList<Element>();
        NodeList nodes = root.getChildNodes();
        Node node;
        int len = nodes.getLength();
        for (int i = 0; i < len; i++) {
            node = nodes.item(i);
            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            // is this the node we're looking for?
            if (node.getNodeName().equals(tagName)) {
                Element element = (Element) node;
                String attr = element.getAttribute(keyAttributeName);

                if (attr != null && attr.equals(keyAttributeValue))
                    result.add(element);
            }

            // look inside.

            List<Element> childs = locateElements((Element) node, tagName, keyAttributeName, keyAttributeValue);

            if (childs != null)
                result.addAll(childs);

        }

        return result;
    }

    /**
     * Extracts from node the attribute with the specified name.
     * @param node the node whose attribute we'd like to extract.
     * @param name the name of the attribute to extract.
     * @return a String containing the trimmed value of the attribute or null
     * if no such attribute exists
     */
    public static String getAttribute(Node node, String name) {
        if (node == null)
            return null;

        Node attribute = node.getAttributes().getNamedItem(name);
        return (attribute == null) ? null : attribute.getNodeValue().trim();
    }
}