Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Copyright 1999-2009 The Pegadi Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.w3c.dom.*;

public class Main {
    /**
     * This methods extracts the text for a named element under the
     * <code>root</code>. For the moment it uses only the first text node,
     * and only the first element of that type.
     *
     * @param root    The element is contained within this root.
     * @param tagname The elemet name to search for
     * @return The text under the tag, or <code>null</code> if it is not found
     *         or an error occured.
     */
    public static String getElementText(Element root, String tagname) {
        NodeList nameList = root.getElementsByTagName(tagname);

        if (nameList.getLength() > 0) {
            Node text = nameList.item(0).getFirstChild();

            // Find the first text node
            while ((text != null) && !(text instanceof Text)) {
                text = text.getNextSibling();
            }

            if (text == null) {
                return null;
            } else {
                try {
                    return text.getNodeValue();
                } catch (DOMException de) {
                    return null;
                }
            }
        } else {
            return null;
        }
    }
}