Java XML Attribute from Node getNodeAttr(String attrName, Node node)

Here you can find the source of getNodeAttr(String attrName, Node node)

Description

Returns the value of the attribute for the given node.

License

Open Source License

Parameter

Parameter Description
attrName the name of the attribute
node the given node

Return

the value of the attribute for the given node

Declaration

public static String getNodeAttr(String attrName, Node node) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**//from  www.j  a v a 2s .c om
     * Returns the value of the attribute for the given node.
     * 
     * @param attrName
     *            the name of the attribute
     * @param node
     *            the given node
     * 
     * @return the value of the attribute for the given node
     */
    public static String getNodeAttr(String attrName, Node node) {
        NamedNodeMap attrs = node.getAttributes();
        for (int y = 0; y < attrs.getLength(); y++) {
            Node attr = attrs.item(y);
            if (attr.getNodeName().equalsIgnoreCase(attrName)) {
                return attr.getNodeValue();
            }
        }
        return "";
    }

    /**
     * Return the string value of the given node (eventually empty).
     * 
     * @param node
     *            a node
     * @return the string value of the given node
     */
    public static String getNodeValue(Node node) {
        NodeList childNodes = node.getChildNodes();
        for (int x = 0; x < childNodes.getLength(); x++) {
            Node data = childNodes.item(x);
            if (data.getNodeType() == Node.TEXT_NODE)
                return data.getNodeValue();
        }
        return "";
    }
}

Related

  1. getIntegerAttribute(Node node, String att_name)
  2. getLongAttributeByName(Node node, String name, long defaultValue)
  3. getLowerAttrValue(Node node, String attr)
  4. getNextSiblingElement(Node node, String elemName, String attrName, String attrValue)
  5. getNodeAttr(String attrName, Node node)
  6. getNodeAttr(String tagName, String attrName, NodeList nodes)
  7. getNodeAttribute(Node n, String as)
  8. getNodeAttribute(Node n, String attrName)
  9. getNodeAttribute(Node n, String name)