get Node Boolean Value from XML Node - Java XML

Java examples for XML:DOM Node Value

Description

get Node Boolean Value from XML Node

Demo Code


import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    public static boolean getNodeBooleanValue(Node node)
            throws XMLHelperException {
        try {//w  ww. ja  v a 2  s.c om
            return Boolean.parseBoolean(getNodeValue(node));
        } catch (NumberFormatException e) {
            throw new XMLHelperException("value of \"" + node.getNodeName()
                    + "\" must be a boolean");
        }
    }
    public static String getNodeValue(Node node) throws XMLHelperException {
        NodeList childNodes = node.getChildNodes();
        if (childNodes.getLength() > 1)
            throw new XMLHelperException(
                    "can't read value - multiple child nodes");
        Node textNode = childNodes.item(0);
        if (textNode.getNodeType() != Node.TEXT_NODE)
            throw new XMLHelperException(
                    "can't read value - child node must be a text node");
        return textNode.getNodeValue().trim();
    }
}

Related Tutorials