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

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

Description

Get attribute value with the given name defined for the specified element.

License

Open Source License

Parameter

Parameter Description
element an Element object.
attrName a name of an attribute

Return

the attribute value.

Declaration

public static String getAttributeValue(Element element, String attrName) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2002-2005 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  ww  w  .jav a  2s . com
 *   IBM - Initial API and implementation
 *******************************************************************************/

import org.w3c.dom.Attr;

import org.w3c.dom.Element;

public class Main {
    /**
     * Get attribute value with the given name defined for the specified element.
     * 
     * @param element an Element object.
     * @param attrName a name of an attribute
     * @return the attribute value.
     */
    public static String getAttributeValue(Element element, String attrName) {
        String attrValue = null;
        Attr attr = null;

        // Get the attribute using its name
        if ((attr = element.getAttributeNode(attrName)) != null) {
            attrValue = attr.getValue().trim();
        }

        // Return attribute value
        return attrValue;
    }

    /**
     * Get attribute value.
     * 
     * @param element an Element object.
     * @param attrName a name of an attribute
     * @param defaultValue a default value for the specified attribute.
     * @return the attribute value if found. Otherwise the specified default
     *         value.
     */
    public static String getAttributeValue(Element element, String attrName, String defaultValue) {
        String returnValue = defaultValue;
        String attrValue = null;

        if ((attrValue = getAttributeValue(element, attrName)) != null)
            returnValue = attrValue;

        return returnValue;
    }
}

Related

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