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 org.w3c.dom.*;

public class Main {
    /**
     * Looks through all child elements of the specified root (recursively)
     * and returns the first element 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 the Element in the tree under root that matches the specified
     * parameters.
     * @throws NullPointerException if any of the arguments is null.
     */
    public static Element locateElement(Element root, String tagName, String keyAttributeName,
            String keyAttributeValue) {
        NodeList nodes = root.getChildNodes();
        int len = nodes.getLength();

        for (int i = 0; i < len; i++) {
            Node node = nodes.item(i);

            if (node.getNodeType() != Node.ELEMENT_NODE)
                continue;

            Element element = (Element) node;

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

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

            //look inside.
            Element child = locateElement(element, tagName, keyAttributeName, keyAttributeValue);

            if (child != null)
                return child;
        }
        return null;
    }

    /**
     * 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();
    }
}