Get value of specified XML attribute as boolean. - Java XML

Java examples for XML:XML Attribute

Description

Get value of specified XML attribute as boolean.

Demo Code


//package com.java2s;
import org.w3c.dom.DOMException;
import org.w3c.dom.NamedNodeMap;

public class Main {
    /**//from  w  ww  .  ja v a  2s  . c om
     * Get value of specified attribute as boolean. If attribute isn't defined return defValue.
     * @param attribs NamedNodeMap
     * @param attributeName String
     * @param defValue boolean
     * @return boolean
     * @throws DOMException
     */
    public static boolean getAttributeValueAsBoolean(NamedNodeMap attribs,
            String attributeName, boolean defValue) throws DOMException {
        String v = getAttributeValue(attribs, attributeName);
        boolean result = defValue;

        if (v != null) {
            try {
                result = "true".equalsIgnoreCase(v)
                        || "yes".equalsIgnoreCase(v);
            } catch (NumberFormatException ex) {
            }
        }
        return result;
    }

    /**
     * Get string value of specified attribute. Return null if attribute isn't defined.
     * @param attribs NamedNodeMap
     * @param attributeName String
     * @return String
     * @throws DOMException
     */
    public static String getAttributeValue(NamedNodeMap attribs,
            String attributeName) throws DOMException {
        String value = null;
        if (attribs.getNamedItem(attributeName) != null) {
            value = attribs.getNamedItem(attributeName).getNodeValue();
        }
        return value;
    }

    /**
     * Get string value of specified attribute. If attribute isn't defined return defValue.
     * @param attribs NamedNodeMap
     * @param attributeName String
     * @param defValue String
     * @return String
     * @throws DOMException
     */
    public static String getAttributeValue(NamedNodeMap attribs,
            String attributeName, String defValue) throws DOMException {
        if (attribs.getNamedItem(attributeName) != null) {
            return attribs.getNamedItem(attributeName).getNodeValue();
        } else {
            return defValue;
        }
    }
}

Related Tutorials