Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.w3c.dom.Attr;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**
     * Gets value of an attribute from node
     * 
     * @param node
     *            Node Object
     * @param attributeName
     *            Attribute Name
     * @return Attribute Value
     * @throws IllegalArgumentException
     *             for Invalid input
     */
    public static String getAttribute(final Node node, final String attributeName) throws IllegalArgumentException {
        // Validate attribute name
        if (attributeName == null) {
            throw new IllegalArgumentException("Attribute Name cannot be null in XmlUtils.getAttribute method");
        }

        // Validate node
        if (node == null) {
            throw new IllegalArgumentException(
                    "Node cannot be null in XmlUtils.getAttribute method for attribute name:" + attributeName);
        }

        final NamedNodeMap attributeList = node.getAttributes();
        if (attributeList != null) {
            final Node attribute = attributeList.getNamedItem(attributeName);
            return attribute == null ? null : ((Attr) attribute).getValue();
        } else {
            return null;
        }

    }

    /**
     * Gets value of an attribute from node. Returns default value if attribute
     * not found.
     * 
     * @param node
     *            Node Object
     * @param attributeName
     *            Attribute Name
     * @param defaultValue
     *            Default value if attribute not found
     * @return Attribute Value
     * @throws IllegalArgumentException
     *             for Invalid input
     */
    public static String getAttribute(final Node node, final String attributeName, final String defaultValue)
            throws IllegalArgumentException {
        // Validate attribute name
        if (attributeName == null) {
            throw new IllegalArgumentException(
                    "Attribute Name " + " cannot be null in XmlUtils.getAttribute method");
        }

        // Validate node
        if (node == null) {
            throw new IllegalArgumentException("Node cannot " + " be null in XmlUtils.getAttribute method for "
                    + "Attribute Name:" + attributeName);
        }

        final NamedNodeMap attributeList = node.getAttributes();
        final Node attribute = attributeList.getNamedItem(attributeName);

        // Validate attribute name
        if (attribute == null) {
            return defaultValue;
        }

        return ((Attr) attribute).getValue();
    }
}