Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Document;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Gets the date between an opening and closing xml tag. E.g. for
     * <tag>xyz</tag> the string xyz would be returned. If there are multiple
     * nodes with the specified tag name, the data of the first node found will
     * be returned.
     * 
     * @param doc
     *            a document.
     * @param tagname
     *            the name of the tag.
     * @return the data of the tag or <code>null</code> if no node with the
     *         specified tag name could be found.
     */
    public static String getTagData(Document doc, String tagname) {
        Node node = getNode(doc, tagname);
        if (node != null) {
            Node child = node.getFirstChild();
            if (child != null) {
                return child.getNodeValue();
            }
        }
        return null;
    }

    /**
     * Gets the first node with the specified tag name from the given document.
     * If there are multiple nodes with the specified tag name, the first node
     * found will be returned.
     * 
     * @param doc
     *            the document
     * @param tagname
     *            the tag name of the node to find.
     * @return the first node found with the specified tag name or
     *         <code>null</code> if no node with that name could be found.
     */
    public static Node getNode(Document doc, String tagname) {
        NodeList nl = doc.getElementsByTagName(tagname);
        if (!isEmpty(nl)) {
            return nl.item(0);
        }
        return null;
    }

    /**
     * Null-safe check if a nodelist is empty.
     * 
     * @param nodeList
     *            the nodelist to check.
     * @return <code>true</code> if the given nodelist is <code>null</code> or
     *         empty.
     */
    public static boolean isEmpty(NodeList nodeList) {
        return nodeList == null || nodeList.getLength() == 0;
    }
}