Returns the value of an attribute in the first XML element in a document with a given tag name. - Java XML

Java examples for XML:XML Attribute

Description

Returns the value of an attribute in the first XML element in a document with a given tag name.

Demo Code


//package com.java2s;
import org.w3c.dom.*;

public class Main {
    /**//from  w ww . ja va  2 s.  c  o m
     * Returns the value of an attribute in the first element in a document with a given tag name.
     * This is useful for well structured documents when it is known that there is only
     * one such element and that it is has that attribute.
     * 
     * @param document The document to search within.
     * @param tagname The name of the element to access.
     * @param attributename The attribute's name.
     * @return The value of the attribute of the first respective element, or the empty string, if
     * the element of the attribute could not be found.
     */
    public static String getAttribute(Document document, String tagname,
            String attributename) {
        NodeList list = document.getElementsByTagName(tagname);
        if (list.getLength() < 1) {
            return "";
        }
        Element tag = (Element) list.item(0);
        return tag.getAttribute(attributename);
    }
}

Related Tutorials