Returns the value of the given XML attribute of the also-given node. - Java XML

Java examples for XML:XML Node

Description

Returns the value of the given XML attribute of the also-given node.

Demo Code

/*//  w  w  w  . j av  a2  s.  c o m
 * DOMUtil.java
 * Copyright (C) 2006 Nicholas Killewald
 * Portions Copyright (C) 2005 Patrick Niemeyer
 *
 * This file is distributed under the terms of the BSD license.
 * See the LICENSE file under the toplevel images/ directory for terms.
 */
//package com.java2s;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class Main {
    /**
     * Returns the value of the given attribute of the also-given node.
     *
     * @param node Element to find the attribute from
     * @param name attribute to get
     * @return the string in the specified element, or null if the attribute doesn't exist or if an error occurs
     */
    public static String getSimpleAttributeText(Element node, String name) {
        NamedNodeMap nnm = node.getAttributes();
        Node n = nnm.getNamedItem(name);
        try {
            return n.getNodeValue();
        } catch (Exception e) {
            return null;
        }
    }
}

Related Tutorials