Code example for Element

Methods: getAttributeNode, getNodeName

0
 
        try { 
            return Integer.parseInt(attValue);
        } catch (Exception ex) {
            if (mandatory) {
                throw new Exception(attName + " attribute of element " + elem.getNodeName()
                    + " must be an integer, but it's '" + attValue + "'");
            } else { 
                return defaultValue;
            } 
        } 
    } 
 
    /** 
     * getIntAttribute purpose. 
     * 
     * <p> 
     * Used to help with XML manipulations. Returns the first child integer 
     * attribute of the specified name.  An exception occurs when the node is 
     * required and not found. 
     * </p> 
     * 
     * @param elem The root element to look for children in. 
     * @param attName The name of the attribute to look for. 
     * @param mandatory true when an exception should be thrown if the 
     *        attribute element does not exist. 
     * 
     * @return The value if the attribute was found, the null otherwise. 
     * 
     * @throws Exception When a child attribute is required and 
     *         not found. 
     * @throws NullPointerException DOCUMENT ME! 
     */ 
    public static String getAttribute(Element elem, String attName, boolean mandatory)
        throws Exception { 
        if (elem == null) {
            if (mandatory) {
                throw new NullPointerException();
            } 
 
            return ""; 
        } 
 
        Attr att = elem.getAttributeNode(attName);
 
        String value = null;
 
        if (att != null) {
            value = att.getValue();
        } 
 
        if (mandatory) {
            if (att == null) {
                throw new Exception("element " + elem.getNodeName()
                    + " does not contains an attribute named " + attName);
            } else if ("".equals(value)) {
                throw new Exception("attribute " + attName + "in element " + elem.getNodeName()
                    + " is empty"); 
            } 
        } 
 
        return value;