Java XML Attribute Get getAttributeValue(Element element, String name)

Here you can find the source of getAttributeValue(Element element, String name)

Description

Get element's attribute value or null if attribute not found or empty.

License

Open Source License

Declaration

public static String getAttributeValue(Element element, String name) 

Method Source Code

//package com.java2s;
/**/*from  www .j a  v a2s  . com*/
 * This file is part of SIMPL4(http://simpl4.org).
 *
 *    Copyright [2014] [Manfred Sattler] <manfred@ms123.org>
 *
 * SIMPL4 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.
 *
 * SIMPL4 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 SIMPL4.  If not, see <http://www.gnu.org/licenses/>.
 */

import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**
     * Returns attribute value of a node or <code>null</code> if attribute name not found.
     * Specified attribute is searched on every call.
     * Consider {@link #getAllAttributes(org.w3c.dom.Node)} for better performances.
     */
    public static String getAttributeValue(Node node, String attrName) {
        NamedNodeMap nmm = node.getAttributes();
        for (int j = 0; j < nmm.getLength(); j++) {
            Node attribute = nmm.item(j);
            if (attribute.getNodeType() != Node.ATTRIBUTE_NODE) {
                continue;
            }
            String nodeName = attribute.getNodeName();
            if (nodeName.equals(attrName)) {
                return attribute.getNodeValue();
            }
        }
        return null;
    }

    /**
     * Get element's attribute value or <code>null</code> if attribute not found or empty.
     */
    public static String getAttributeValue(Element element, String name) {
        String value = element.getAttribute(name);
        if (value.length() == 0) {
            value = null;
        }
        return value;
    }
}

Related

  1. getAttributeValue(Element element, String attr)
  2. getAttributeValue(Element element, String attributeName)
  3. getAttributeValue(Element element, String attributeName, String namespaceURI)
  4. getAttributeValue(Element element, String attrName)
  5. getAttributeValue(Element element, String attrName)
  6. getAttributeValue(Element element, String name)
  7. getAttributeValue(Element element, String tag)
  8. getAttributeValue(final Element e, final String attributeName)
  9. getAttributeValue(final Element el, final String attrName)