Get the attribute value under the specified name from the given XML element. - Java XML

Java examples for XML:XML Attribute

Description

Get the attribute value under the specified name from the given XML element.

Demo Code

/*/*from   w  w w.  j  a v a 2  s.  co  m*/
   Copyright (C) 2016 HermeneutiX.org

   This file is part of SciToS.

   SciToS is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   SciToS is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with SciToS. If not, see <http://www.gnu.org/licenses/>.
 */
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main{
    /**
     * Get the attribute value under the specified name from the given element. Parsing it as an Integer.
     *
     * @param node
     *            element to retrieve the attribute value from
     * @param attributeName
     *            name of the targeted attribute
     * @param defaultValue
     *            value to return if attribute doesn't exist or cannot be parsed to an Integer
     * @return either retrieved or given default value
     */
    public static int getIntAttribute(final Element node,
            final String attributeName, final int defaultValue) {
        final String stringValue = DomUtil.getNullableAttribute(node,
                attributeName);
        if (stringValue != null) {
            try {
                return Integer.parseInt(stringValue);
            } catch (final NumberFormatException expected) {
                // fall back on default value
            }
        }
        return defaultValue;
    }
    /**
     * Get the attribute value under the specified name from the given element.
     *
     * @param node
     *            element to retrieve the attribute value from
     * @param attributeName
     *            name of the targeted attribute
     * @return the attribute's value (or {@code null} if no such attribute exists)
     */
    public static String getNullableAttribute(final Element node,
            final String attributeName) {
        if (node.hasAttribute(attributeName)) {
            return node.getAttribute(attributeName);
        }
        return null;
    }
}

Related Tutorials