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

Java examples for XML:XML Attribute

Description

Get value of specified XML attribute as double.

Demo Code


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

public class Main {
    /**//  w  w  w  .j  av a2  s . com
     * Get value of specified attribute as double. If attribute isn't defined return defValue.
     * @param attribs NamedNodeMap
     * @param attributeName String
     * @param defValue double
     * @return double
     * @throws DOMException
     */
    public static double getAttributeValueAsDouble(NamedNodeMap attribs,
            String attributeName, double defValue) throws DOMException {
        String v = getAttributeValue(attribs, attributeName);
        double result = defValue;

        if (v != null) {
            try {
                result = Double.parseDouble(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