Java XML Attribute from Element getElementAttribute(Element root, String elemName, String att)

Here you can find the source of getElementAttribute(Element root, String elemName, String att)

Description

get the value of an Attribute in the Xml Document.

License

Open Source License

Parameter

Parameter Description
root the root Element.
elemName the name of the element to search for.
att the name of the attribute to search for.

Return

String the attribute value or null if not found.

Declaration

public static String getElementAttribute(Element root, String elemName, String att) 

Method Source Code

//package com.java2s;

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

public class Main {
    /**/*from ww w  .j  a  va2  s  .co m*/
     * get the value of an Attribute in the Xml Document.
     * finds the first occurance of the parent element and then searches its attributes
     * for the occurance of the attribute and retrieves its value.
     * @param root the root Element.
     * @param elemName the name of the element to search for.
     * @param att the name of the attribute  to search for.
     * @return String the attribute value or null if not found.
     */
    public static String getElementAttribute(Element root, String elemName, String att) {
        NodeList nl = root.getElementsByTagName(elemName);
        if (null == nl) {
            return (null);
        }
        Node n = nl.item(0);
        if (null == n) {
            return (null);
        }
        NamedNodeMap attributes = n.getAttributes();
        if (null == attributes) {
            return (null);
        }
        n = attributes.getNamedItem(att);
        if (null == n) {
            return (null);
        }
        return (n.getNodeValue().trim());

    }
}

Related

  1. getElementArrayInt(Element root, String name, String attrib)
  2. getElementArrayString(Element root, String name, String attrib)
  3. getElementAttr(Element element, String attr)
  4. getElementAttribute(Element element, String name)
  5. getElementAttribute(Element root, String elementName, String attribute)
  6. getElementAttributes(Element element, List exclude)
  7. getElementAttributeValue(Element element, String attributeName)
  8. getElementBooleanValue(Element element, String attribute)
  9. getElementBooleanValue(Element element, String attribute)