get Value from Node with default value - Java XML

Java examples for XML:DOM Node Value

Description

get Value from Node with default value

Demo Code


//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static int getValue(final Node node, final String strAttrName,
            final String strAttrValue, final int iDefaultValue) {
        final String strValue = getValue(node.getChildNodes(), strAttrName,
                strAttrValue);// w  w  w.jav a 2s.  com

        if (strValue == null) {
            return iDefaultValue;
        }

        return Integer.parseInt(strValue);
    }

    public static double getValue(final Node node,
            final String strAttrName, final String strAttrValue,
            final double dDefaultValue) {
        final String strValue = getValue(node.getChildNodes(), strAttrName,
                strAttrValue);

        if (strValue == null) {
            return dDefaultValue;
        }

        return Double.parseDouble(strValue);
    }

    public static String getValue(final Node node,
            final String strAttrName, final String strAttrValue) {
        return getValue(node.getChildNodes(), strAttrName, strAttrValue);
    }

    public static String getValue(final NodeList nodes,
            final String strAttrName, final String strAttrValue) {
        for (int i = 0; i < nodes.getLength(); ++i) {
            final Node node = nodes.item(i);

            if (node instanceof Element) {
                final Element elem = (Element) node;

                if (strAttrValue.equals(elem.getAttribute(strAttrName))) {
                    return elem.getLastChild().getTextContent().trim();
                }
            }
        } // end for

        return null;
    }
}

Related Tutorials